ECMA 2022 新特性

403 阅读2分钟

前言

2022 年 6 月 22 日,第 123 届 Ecma 大会批准了 ECMAScript 2022 语言规范,也就是说es2022正式成为新的官方标准

新特性

new member of classes

变量可以快速创建而不必须通过构造函数

    class Test {
        instancePublicFiled = 0;
        
        constructor (value) {
            this.publicPropertyA = value;
        }
    }
    
    const inst = new Test('constrArg');
    // true
    assert.deepEqual(
      Reflect.ownKeys(inst),
      ['instancePublicField', 'publicPropertyA']
    );

私有变量和私有方法

通过#将变量或方法标记为私有,外部访问会报错

class MyClass {
  static staticPublicField = 2;

  #instancePrivateField = 3;
  static #staticPrivateField = 4;

  #nonStaticPrivateMethod() {}
  get #nonStaticPrivateAccessor() {}
  set #nonStaticPrivateAccessor(value) {}

  static #staticPrivateMethod() {}
  static get #staticPrivateAccessor() {}
  static set #staticPrivateAccessor(value) {}

  static {
    // Static initialization block
  }
}

私有字段存在新检查

通过#privateSlot in obj检查对象是否存在私有字段

Top-level await in module

可以在模块的顶层直接使用await不需要再配合async使用

// my-module.mjs
const response = await fetch('https://example.com');
const text = await response.text();
console.log(text);

error.casue

允许通过error.cause将错误进行链式串接

async function testCatchCause() {
  const rawResource = await fetch('/test')
    .catch(err => {
      throw new Error('失败', { cause: err });
    });
}

try {
  await testCatchCause();
} catch (e) {
  console.log(e);
  console.log('Caused by', e.cause);
}
// Error: 失败
// Caused by TypeError: Failed to fetch

at()

从指定索引处读取元素,与直接array[index]的区别at()方法支持负索引已从数组末尾开始读取元素

String、Array、TypeArrar都支持该方法

const array = [1,2,3,4,5]
// 5
console.log(array.at(-1))

RegExp match indices

增加了一个新的匹配模式/d,返回每一个捕获组的开始和结束index

const matchObj = /(a+)(b+)/d.exec('aaaabb');

assert.equal(
  matchObj[1], 'aaaa'
);
assert.deepEqual(
  matchObj.indices[1], [0, 4] // (A)
);

assert.equal(
  matchObj[2], 'bb'
);
assert.deepEqual(
  matchObj.indices[2], [4, 6] // (B)
);

indices[0]是全部字符串的匹配信息,后续为每个捕获组的匹配信息

Object.hasOwn(obj, propKey)

新增Object.hasOwn方法是一个比Object.property.hasOwnProperty更安全可靠的用来指示对象自身属性中是否具有指定的属性的方法

Object.property.hasOwnProperty 存在的问题

当创建的对象存在hasOwnProperty时,hasOwnProperty无法正确返回作用

const obj = {
  // Overrides Object.prototype.hasOwnProperty
  hasOwnProperty: true,
};

obj.hasOwnProperty('xxx') // true