原文:4 most important features coming in ES2022 that you should know about
image.png

ES2022中4个最重要的特性

ECMAScript 2022是新的JS标准 ,将会在2022年的6月份发布。

1、数组中的at()方法

ES2022将会提供从末尾索引类数组对象的能力。
这是一个比较小的特性,但是提高了代码的可读性,当我们在处理arraysstrings

At()方法中,当传递正数时,和[]的作用一致;当传递负数的时候,将从末尾往前索引访问值。

用于替换如下写法:

  1. const arr = [1,2,3,4]
  2. arr[arr.length - 2] // 3
  3. arr.slice(-2)[0] // 3
  4. const str = "1234"
  5. str[str.length - 2] // '3'
  6. str.slice(-2)[0] // '3'

新的写法:

  1. const arr = [1,2,3,4]
  2. arr.at(-2) // 3
  3. const str = "1234"
  4. str.at(-2) // '3'

2、Error Cause

error对象的.cause属性,允许我们明确制定是有哪个错误引发了其他的错误。
看下面的例子:

  1. try {
  2. doSomeComputationThatThrowAnError()
  3. } catch (error) {
  4. throw new Error('I am the result of another error', { cause: error })
  5. }

Error Casue提供了一种完美的方式,帮助我们把error链接到一起。

3、最顶层的await

首先,await是不能在function外面直接用的。ES2022将会支持在function外面提供直接使用的能力。

这能做什么?

  • 动态的载入模块 ``javascript const serviceName = await fetch("https://example.com/what-service-should-i-use") const service = await import(/services/${serviceName}.js`)

// OR

const params = new URLSearchParams(location.search); const theme = params.get(‘theme’); const stylingFunctions = await import(/styling-functions-${theme}.js);

  1. - _**条件渲染模块**_
  2. ```javascript
  3. const date = new Date()
  4. if(date.getFullYear() === 2023) {
  5. await require('/special-code-for-2023-year.js')
  6. }

4、私有插槽和方法

自从ES6发布后,Class就出现在原生JS中了,但是相比面向对象的语言,应用场景相对较少。很多的开发者会使用TS的能力由于替代,现在JS提供了原生实现。

私有插槽是其中之一。这个无非就是Class的私有属性。ES2022给与我们创建它们的能力,当我们从CLass的外部访问它们时,就会报错。私有方法也是一样的。JS团队选择了#号这个前缀。

  1. class Human {
  2. #name = "John";
  3. setName(name) {
  4. this.#name = name;
  5. }
  6. }
  7. const human = new Human()
  8. human.#name = 'Amy' // ERROR!
  9. human.setName('Amy') // OK

私有方法:

  1. class Human {
  2. name = "John";
  3. constructor(name) {
  4. this.#setName('Amy') // OK
  5. }
  6. #setName(name) {
  7. this.name = name;
  8. }
  9. }
  10. const human = new Human()
  11. human.#setName('Amy') // ERROR!

完整介绍可以查看:

New in ECMAScript 2022