茶已备好,只待君来!感谢关注 前端点线面 (>‿<),本号干货满满:14个门类(100+篇原创)内容——又干又硬、《前端百题斩》pdf——助力薪资double、20+篇思维导图——知识系统化、记忆简单化;加我进卧虎藏龙摸鱼群,一起划水一起嗨!!!
很快,新版本的 ECMA Script 将在几个月内成为标准。那么让我们来看看将成为 ES2022 一部分的特性。
ES2022 的新功能
1、.at()索引值对应值的方法。
这个函数让我们读取给定索引处的元素。它可以接受负索引来从给定数据类型的末尾读取元素。
例如
[1,2,3,4,5].at(3) // returns 4
[1,2,3,4,5].at(-2) // returns 4
支持此功能的数据类型有以下:
String
Array
所有类型化数组类:Uint8Array 等。
2、 RegExp 匹配索引
除了g
、i
,正则表达式新增d
标志会生成匹配对象,记录每个组捕获的开始和结束。
有不同的方法来匹配索引
编号组的匹配索引
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 记录输入字符串中捕获的每个编号组。
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
matchObj.indices.groups;
/*
Output -
{ as: [0,4], bs: [4,6] }
*/
3、Object.hasOwn(obj, propKey)
这是检查obj
对象自身属性propKey
的一种安全方法。它类似于Object.prototype.hasOwnProperty
但它支持所有对象类型。
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.
4、error.cause
通过分析错误及其子类让我们指定错误背后的原因。
function readFiles(filePaths) {
return filePaths.map(
(filePath) => {
try {
// ···
} catch (error) {
throw new Error(
`While processing ${filePath}`,
{cause: error}
);
}
});
}
5、 顶层 await
以前当 async/await
首次引用时,尝试在 async
函数外部使用 await
的结果是产生 SyntaxError
错误。所以大多数开发者使用立即执行异步函数表达式的方式来使用该功能,现在不需要了。
动态加载模块
const messages = await import(`./messages-${language}.mjs`);
如果模块加载失败,使用回退
let lodash;
try {
lodash = await import('https://primary.example.com/lodash');
} catch {
lodash = await import('https://secondary.example.com/lodash');
}
使用加载速度最快的资源
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新成员
公共属性可以通过实例公共字段创建
class InstPublicClass {
// 实例公共字段
instancePublicField = 0; // (A)
constructor(value) {
// 我们不需要在其他地方提及 .property!
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
实例私有字段
class InstPrivateClass {
#privateField1 = 'private field 1'; // (A)
#privateField2; // (B) required!
constructor(value) {
this.#privateField2 = value; // (C)
}
/**
* 私有字段在类主体之外是不可访问的。
*/
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)
}
/**
* 私有字段在类主体之外是不可访问的
*/
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"]
私有slot检查- 此功能帮助我们检查对象中是否有给定的私有slot。
class C1 {
#priv() {}
static check(obj) {
return #priv in obj;
}
}
console.log(C1.check(new C1())) // output true
这些惊人的功能将帮助我们增强我们的项目并改进我们的编码技术。💃快乐编码!👩🏻💻
··············· 执鸢者简介 ·················
看号主详细信息,来这
畅所欲言交流群
【1】前端百题斩系列
【2】Vue系列
【3】React系列
【4】前端基础系列
【5】基础知识
【6】浏览器系列
【7】构建工具系列
【8】网络系列
【9】Node系列
【10】源码系列
【11】前端有意思
【12】手撕算法系列
【13】个人总结
【14】杂科