ECMAScript 2022 (13)
特性一览
顶层 await
在 ECMAScript2022 以前,我们需要在使用 立即执行函数表达式
来实现顶层 async/await 操作。
js
(async () => {
//...await...
})();
ECMAScript2022 允许在模块的顶层可以使用 async 和 await 关键字,可以直接等待一个异步操作完成。
js
import {getUser} from './data/User'
let user=await getUser();
Class 语法补充
- 公有和私有实例字段
在 ECMAScript2022 以前,在构造函数内的变量前加一条下划线_
表示私有实例字段,意味着只能从类方法内部访问,但是即使在外部访问也不会报错。
js
class ButtonToggle {
constructor() {
this.color = "green"; // 公有实例字段
this._value = true; // 私有实例字段//[!code focus]
}
toggle() {
this.value = !this.value;
}
}
const button = new ButtonToggle();
button.color;
// 无报错
button._value = false;
ECMAScript2022 使用#
表示私有实例字段,不再需要构造函数
js
class ButtonToggle {
color = "green"; // 公有实例字段
#value = true; // 私有实例字段//[!code focus]
toggle() {
this.#value = !this.#value;
}
}
const button = new ButtonToggle();
button.color;
// 报私有字段或方法错误
button.#value;
button.#value = false;
- 私有实例方法和访问器
js
class ButtonToggle {
get #getElement(){}
set #setElement(){}
}
- 静态公共字段和方法
js
class ButtonToggle {
static element = "#btn";
static getElement() {}
}
ButtonToggle.element;
ButtonToggle.getElement();
- 静态私有字段和方法
js
class ButtonToggle {
static #element = "#btn";
static getElement() {
return this.#element;
}
}
ButtonToggle.getElement(); // '#btn'
私有字段 in
语法
通过私有字段的 in
语法,检查对象实例是否包含一个确定的私有字段。
js
class MyClass {
#name = "Alice";
}
const obj = new MyClass();
"#name" in obj; // true
"#age" in obj; // false
正则 /d
匹配索引
exec 和 matchAll 可以用来查找匹配列表,区别是逐一返回其结果和返回一个迭代器,但是没有拿到索引
js
const fruits = "Fruits: mango, mangosteen, orange";
const regex = /(mango)/g;
// [
// 'mango',
// index: 8,
// input: 'Fruits: mango, mangosteen, orange',
// groups: undefined
// ]
RegExp(regex).exec(fruits);
const matches = [...fruits.matchAll(regex)];
// [
// 'mango',
// 'mango',
// index: 8,
// input: 'Fruits: mango, mangosteen, orange',
// groups: undefined
// ]
matches[0];
/d
拿到正则匹配项的索引(开始和结束)。
js
const fruits = "Fruits: mango, mangosteen, orange";
const regex = /(mango)/dg;
const matches = [...fruits.matchAll(regex)];
// [
// "mango",
// "mango",
// groups: undefined
// index: 8
// indices:[]
// [8, 13], //[!code focus]
// [8, 13] //[!code focus]
// ]
matches[0];
异常处理新增 cause 属性
ECMAScript2022 提出使用 cause 来收集错误原因
js
new Promise().catch((err) => {
throw new Error("失败", { cause: err });
});
字符串、数组的 at()
访问数组/字符串的指定位置
以前:
js
const array = [1, 2, 3, 4, 5];
array[array.length - 1]; //5
ECMAScript2022:
js
const array = [1, 2, 3, 4, 5];
array.at(-1); //5 //[!code focus]
Object.hasOwn()
对象可以有 hasOwnProperty 属性,导致可以直接使用(不安全)
js
const obj = {
hasOwnProperty: () => false,
};
obj.hasOwnProperty("hahaha"); //永远是false
ECMAScript2022 提出使用 Object.hasOwn()
解决 hasOwnProperty 导致的问题。
js
const obj = {
hasOwn: () => false,
};
Object.hasOwn(obj, "hasOwn"); //true //[!code focus]