A new version of ECMA Script will become standard within a few months. So let's take a look at the features that will be part of ES2022
1. .at()
method for indexable values
This function lets us read the element at the given index. It can accept negative indices to read elements from the end of a given data type
[1,2,3,4,5].at(3) // 4
[1,2,3,4,5].at(-2) // 4
Data types that support this feature
- String
*Array - All Typed Array classes: Uint8Array etc.
2.RegExp match index
/d
adding flags to the regex produces a match object, recording the start and end of each group capture
There are different ways to match the index
const matchObj = /(a+)(b+)/d.exec('aaaabb');
console.log(matchObj);
/*
Output -
['aaaabb', 'aaaa', 'bb', index: 0, input: 'aaaabb', groups: undefined, indices: Array(3)]
*/
matchObj.indices[1];
/*
Output -
[0, 4]
*/
const matchObj = /(?<as>a+)(?<bs>b+)/d.exec('aaaabb');
console.log(matchObj);
/*
Output -
['aaaabb', 'aaaa', 'bb', index: 0, input: 'aaaabb', groups: {as: 'aaaa', bs: 'bb'}, indices: Array(3)]
*/
matchObj.indices.groups;
/*
Output -
{ as: [0,4], bs: [4,6] }
*/
Object.hasOwn(obj, propKey)
This is a safe way to inspect the propKey object's own properties obj. It is similar to Object.prototype.hasOwnProperty but it supports all object types
const proto = {
protoProp: 'protoProp',
};
const obj = {
__proto__: proto,
objProp: 'objProp',
};
console.log('protoProp' in obj); // output - true.
console.log(Object.hasOwn(obj, 'protoProp')) // output - false
console.log(Object.hasOwn(proto, 'protoProp')); // output - true.
error.cause
Errors and their subclasses Now let's specify the reason behind the error. This is useful in deeply nested functions, where we chain error blocks to quickly find errors
function readFiles(filePaths) {
return filePaths.map(
(filePath) => {
try {
//
} catch (error) {
throw new Error(
`While processing ${filePath}`,
{cause: error}
);
}
});
}
5. Top-level wait module
Dynamically load modules
const messages = await import(`./messages-${language}.mjs`);
Use fallback if module loading fails
let lodash;
try {
lodash = await import('https://primary.example.com/lodash');
} catch {
lodash = await import('https://secondary.example.com/lodash');
}
Use the fastest loading resource
const resource = await Promise.any([
fetch('http://example.com/first.txt')
.then(response => response.text()),
fetch('http://example.com/second.txt')
.then(response => response.text()),
]);
6. Class new members
Public
class InstPublicClass {
// Instance public field
instancePublicField = 0; // (A)
constructor(value) {
// We don't need to mention .property elsewhere!
this.property = value; // (B)
}
}
const inst = new InstPublicClass('constrArg');
const computedFieldKey = Symbol('computedFieldKey');
class StaticPublicFieldClass {
static identifierFieldKey = 1;
static 'quoted field key' = 2;
static[computedFieldKey] = 3;
}
console.log(StaticPublicFieldClass.identifierFieldKey) //output -> 1
console.log(StaticPublicFieldClass['quoted field key']) //output -> 2
console.log(StaticPublicFieldClass[computedFieldKey]) //output -> 3
Private
class InstPrivateClass {
#privateField1 = 'private field 1'; // (A)
#privateField2; // (B) required!
constructor(value) {
this.#privateField2 = value; // (C)
}
/**
* Private fields are not accessible outside the class body.
*/
checkPrivateValues() {
console.log(this.#privateField1); // output -> 'private field 1'
console.log(this.#privateField2); // output -> 'constructor argument'
}
}
const inst = new InstPrivateClass('constructor argument');
inst.checkPrivateValues();
console.log("inst", Object.keys(inst).length === 0) //output -> inst, true
class InstPrivateClass {
#privateField1 = 'private field 1'; // (A)
#privateField2; // (B) required!
static #staticPrivateField = 'hello';
constructor(value) {
this.#privateField2 = value; // (C)
}
/**
* Private fields are not accessible outside the class body.
*/
checkPrivateValues() {
console.log(this.#privateField1); // output -> 'private field 1'
console.log(this.#privateField2); // output -> 'constructor argument'
}
static #twice() {
return this.#staticPrivateField + " " + this.#staticPrivateField;
}
static getResultTwice() {
return this.#twice()
}
}
const inst = new InstPrivateClass('constructor argument');
inst.checkPrivateValues();
console.log("inst", Object.keys(inst).length === 0) //output -> "inst", true
console.log(InstPrivateClass.getResultTwice()); // output -> "hello hello"
class MyClass {
#privateMethod() {}
static check() {
const inst = new MyClass();
console.log(#privateMethod in inst) // output->true
console.log(#privateMethod in MyClass.prototype) // output->false
console.log(#privateMethod in MyClass) // output->false
}
}
MyClass.check();
class Translator {
static translations = {
yes: 'ja',
no: 'nein',
maybe: 'vielleicht',
};
static englishWords = [];
static germanWords = [];
static { // (A)
for (const [english, german] of Object.entries(this.translations)) {
this.englishWords.push(english);
this.germanWords.push(german);
}
}
}
console.log(Translator.englishWords, Translator.germanWords)
//Output ->["yes", "no", "maybe"], ["ja", "nein", "vielleicht"]
class C1 {
#priv() {}
static check(obj) {
return #priv in obj;
}
}
console.log(C1.check(new C1())) // output true
These features will help us enhance our projects and improve our coding techniques. I'm excited to try these functions in my project
Post comment 取消回复