ES2022(ES13)新增特性
1 数组对象新增的属性方法
方法名 | 描述 |
---|---|
at() | 回该指定索引对应的元素,允许正数和负数。负整数从数组中的最后一个元素开始倒数。 |
2 Object 构造函数本身新增属性方法
方法名 | 描述 |
---|---|
Object.hasOwn() | 检查属性是否直接设置在对象上,返回布尔值 |
3 Class 语法新增特性
3.1 类的实例的属性的新语法
ES2022 为类的实例属性,又规定了一种新写法。实例属性现在除了可以定义在constructor()
方法里面的this
上面,也可以定义在类内部的最顶层。
class Incrementor {
count = 0;
name;
}
const inc = new Incrementor();
inc.count; // 0
inc.name; // undefiend
3.2 设置私有属性
ES2022正式为class
添加了私有属性,方法是在属性名之前使用#
表示, 私有属性,只能在类的内部使用,如果在类的外部使用,就会报错。
class IncreasingCounter {
#count = 0;
get value() {
return this.#count;
}
increment() {
this.#count++;
}
}
const counter = new IncreasingCounter();
counter.increment();
counter.#count // 报错
counter.#count = 42 // 报错