ES2022 中的4个最重要的特性


ECMAScript 2022 是一项新的 JavaScript 标准,将于 2022 年 6 月发布。
 
1. 数组中的at()方法
ES2022将为我们提供一种可能性,即从末端索引类似数组的对象。这是一个很小的功能,但它提高了处理数组或字符串时的核心可读性。
At()方法中的正数与[]索引的作用相同,但如果是负数,则允许从末尾访问数值。
原来:

const arr = [1,2,3,4]
arr[arr.length - 2] // 3
arr.slice(-2)[0]    
// 3

const str =
"1234"
str[str.length - 2]
// '3'
str.slice(-2)[0]    
// '3'

新的at()方法:

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

const str =
"1234"
str.at(-2)
// '3'

 
2. 错误原因
.cause对象上的.cause属性将允许我们指定哪个错误导致其他错误。非常不言而喻吧?在这里你可以看到这个新功能的一个使用例子。

try {
  doSomeComputationThatThrowAnError() 
} catch (error) {
  throw new Error('I am the result of another error', { cause: error })
}

错误原因将是一个完美的方法,可以将错误连在一起,这在其他编程语言如Java中是可能的。
 
3. 顶层的await
你知道你不能在函数之外的代码中直接使用await吗?如果不知道,那么这对你来说不是什么大问题。但对于其他人来说--不必担心,因为ES2022将改变这一点。
  • 它允许动态地加载模块

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`);

  • 它允许有条件地渲染模块

const date = new Date()

if(date.getFullYear() === 2023) {
  await require('/special-code-for-2023-year.js')
}

 
4. 私有槽slot和方法
纯Javascript中的类从ES6开始就存在了,但与面向对象的语言相比,它们的开发程度要低很多。许多开发者使用Typescript来包含其中的一些功能,现在我们可以看到在纯Javascript类中被实现。
私有槽是其中之一。它们只不过是类的私有属性。ES2022将为我们提供创建它们的可能性,当我们试图在类之外访问它们时,会得到一个错误。私有方法也是如此。有趣的是,JS团队选择给他们前缀(这与JS的传统有关吗?)
class Human {
  name = "John";
  
  setName(name) {
    this.name = name;
  }
}

const human = new Human()
human.name = 'Amy'  
// ERROR!
human.setName('Amy')
// OK

私有方法:

class Human {
  name = "John";
  
  constructor(name) {
    this.setName('Amy')
// OK
  }
  
  setName(name) {
    this.name = name;
  }
}

const human = new Human()
human.setName('Amy')
// ERROR!