whats-new-in-es2022-1de6

原始地址:https://dev.to/jasmin/whats-new-in-es2022-1de6

## [ES2022的特性](https://dev.to#features-of-es2022)
### 1. 可索引值的`.at()`方法
该函数允许我们读取给定索引位置上的元素。它可以接受负数索引以便从给定数据类型的末尾读取元素。
例如:
[1,2,3,4,5].at(3) // 返回 4
[1,2,3,4,5].at(-2) // 返回 4
支持该函数的数据类型有:
- 字符串
- 数组
- 所有Typed Array类: Uint8Array 等

### 2. 正则表达式匹配索引
给正则表达式添加标志`/d`可以产生记录每个分组捕获开始和结束位置的匹配对象。
有不同的匹配索引的方式:
- **显式数字分组的匹配索引**
```javascript
const matchObj = /(a+)(b+)/d.exec('aaaabb');
console.log(matchObj);
/*
输出 -
['aaaabb', 'aaaa', 'bb', index: 0, input: 'aaaabb', groups: undefined, indices: Array(3)]
*/

由于正则表达式标志/d,matchObj也有一个称为indices的属性,用于记录每个已编号分组在输入字符串中被捕获的位置。

matchObj.indices[1];
/*
输出 -
[0, 4]
*/
  • 命名分组的匹配索引
const matchObj = /(?<as>a+)(?<bs>b+)/d.exec('aaaabb');
console.log(matchObj);
/*
输出 -
['aaaabb', 'aaaa', 'bb', index: 0, input: 'aaaabb', groups: {as: 'aaaa', bs: 'bb'}, indices: Array(3)]
*/

它们的索引存储在matchObj.indices.groups中。

matchObj.indices.groups;
/*
输出 -
{ as: [0,4], bs: [4,6] }
*/

3. Object.hasOwn(obj, propKey)方法

这是一种安全的方式来检查propKey是否是obj对象的自有属性。它类似于Object.prototype.hasOwnProperty,但支持所有对象类型。

const proto = {
  protoProp: 'protoProp',
};
const obj = {
  __proto__: proto,
  objProp: 'objProp',
};
console.log('protoProp' in obj); // 输出 true
console.log(Object.hasOwn(obj, 'protoProp')) // 输出 false
console.log(Object.hasOwn(proto, 'protoProp')); // 输出 true

4. error.cause属性

Error及其子类现在可以让我们指定错误的原因。这对于深层嵌套的函数中有链式错误块的情况非常有用,可以快速找到错误。
在这里阅读更多信息

function readFiles(filePaths) {
  return filePaths.map(
    (filePath) => {
      try {
        // ···
      } catch (error) {
        throw new Error(`While processing ${filePath}`, {cause: error});
      }
    }
  );
}

5. 顶层await模块

我们现在可以在模块的顶层使用await,不再需要进入异步函数或方法。

  • 动态加载模块
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 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) // 输出 1
    console.log(StaticPublicFieldClass['quoted field key']) // 输出 2
    console.log(StaticPublicFieldClass[computedFieldKey]) // 输出 3
    
  • 私有槽是新的,并且可以通过
    • 实例私有字段
    class InstPrivateClass {
      #privateField1 = 'private field 1'; // (A)
      #privateField2; // (B) 必需!
      constructor(value) {
        this.#privateField2 = value; // (C)
      }
      /**
       * 在类体外部无法访问私有字段。
       */
      checkPrivateValues() {
        console.log(this.#privateField1); // 输出 'private field 1'
        console.log(this.#privateField2); // 输出 'constructor argument'
      }
    }
    const inst = new InstPrivateClass('constructor argument');
    inst.checkPrivateValues();
    console.log("inst", Object.keys(inst).length === 0) // 输出 inst, true
    
    • 实例和静态私有字段
    class InstPrivateClass {
      #privateField1 = 'private field 1'; // (A)
      #privateField2; // (B) 必需!
      static #staticPrivateField = 'hello';
      constructor(value) {
        this.#privateField2 = value; // (C)
      }
      /**
       * 在类体外部无法访问私有字段。
       */
      checkPrivateValues() {
        console.log(this.#privateField1); // 输出 'private field 1'
        console.log(this.#privateField2); // 输出 '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) // 输出 "inst", true
    console.log(InstPrivateClass.getResultTwice()); // 输出 "hello hello"
    
    • 私有方法和访问器
    class MyClass {
      #privateMethod() {}
      static check() {
        const inst = new MyClass();
        console.log(#privateMethod in inst) // 输出 true
        console.log(#privateMethod in MyClass.prototype) // 输出 false
        console.log(#privateMethod in MyClass) // 输出 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)
// 输出 ["yes", "no", "maybe"], ["ja", "nein", "vielleicht"]
  • 私有槽检查- 此功能可用于检查对象是否具有给定的私有槽。
class C1 {
  #priv() {}
  static check(obj) {
    return #priv in obj;
  }
}
console.log(C1.check(new C1())) // 输出 true

这些令人惊叹的特性将帮助我们改进项目并提升编码技巧。我非常期待在我的项目中尝试这些特性。 💃

Happy Coding! 👩🏻💻

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值