ES13新增内容
大约 2 分钟JavaScriptES13JavaScript
ES13(ECMAScript 2022)新特性
1. 类字段(Class Fields)
允许在类最外层直接声明类成员。
示例:
class Person {
name = 'Tom';
}
2. 类静态块(Class Static Block)
为静态成员提供了一个用于初始化工作的代码块。
示例:
class C {
static x = 'x';
static y;
static z;
static {
try {
const obj = doSomethingWith(this.x);
this.y = obj.y;
this.z = obj.z;
} catch (err) {
this.y = 'y is error';
this.z = 'z is error';
}
}
}
3. 私有化类成员
支持私有实例、私有静态字段和私有方法。
示例:
class Person {
#privateField1 = 'private field 1'; // 私有字段赋初值
#privateField2; // 默认 undefined
static #privateStaticField3 = 'private static field 3';
constructor(value) {
this.#privateField2 = value; // 实例化时为私有字段赋值
}
#toString() {
console.log(this.#privateField1, this.#privateField2, Person.#privateStaticField3);
}
print() {
this.#toString();
}
}
const p = new Person('private field 2');
p.print(); // 输出:private field 1 private field 2 private static field 3
4. 私有字段检查
使用 in
操作符检测某一实例是否包含要检测的私有字段。
示例:
class Person {
#name = 'Ergonomic brand checks for Private Fields';
static check(obj) {
return #name in obj;
}
}
await
5. 顶层 允许在模块的顶级作用域中使用 await
,仅限于 ES Modules。
示例:
let jQuery;
try {
jQuery = await import('https://cdn-a.com/jQuery');
} catch {
jQuery = await import('https://cdn-b.com/jQuery');
}
/d
修饰符
6. 正则表达式 新增了 /d
修饰符,它会返回一个 indices
属性,包含了匹配元素的开始、结束位置索引。
示例:
const str = 'ECMAScript_JavaScript';
const regexp = /sc/igd; // 忽略大小写全局匹配并返回匹配元素的开始、结束位置索引
console.log(regexp.exec(str).indices[0]); // [ 4, 6 ]
console.log(regexp.exec(str).indices[0]); // [ 15, 17 ]
// 包含组信息
const text = 'zabbcdef';
const re = /ab+(cd(ef))/d;
const result = re.exec(text);
console.log(result.indices); // [ [1, 8], [4, 8], [6, 8] ]
// 具名组匹配
const reNamedGroup = /ab+(?<Z>cd)/d;
const resultNamedGroup = reNamedGroup.exec(text);
console.log(resultNamedGroup.indices.groups); // { Z: [ 4, 6 ] }
.at()
方法
7. 根据指定索引获取数组或字符串中的元素,支持负数索引。
示例:
const arr = ['a', 'b', 'c'];
console.log(arr.at(0)); // a
console.log(arr.at(-1)); // c
Object.hasOwn()
8. 提供了一种更安全的方法来检查对象是否具有自己的属性,避免了 hasOwnProperty
在某些情况下的问题。
示例:
const person = Object.create({ name: 'Tom' });
person.age = 18;
console.log(Object.hasOwn(person, 'name')); // false
console.log(Object.hasOwn(person, 'age')); // true
// hasOwnProperty 遇到这种情况会报错
const p1 = null;
console.log(p1.hasOwnProperty('name')); // TypeError
9. 错误原因(Error Cause)
增加了错误构造函数的一个选项,可以设置 cause
的值为任意有效的 JavaScript 值,以传递错误的原因。
示例:
try {
await fetch().catch(err => {
throw new Error('Request failed', { cause: err });
});
} catch (e) {
console.log(e.message); // Request failed
console.log(e.cause); // 原始错误对象
}