原文:4 most important features coming in ES2022 that you should know about
ES2022中4个最重要的特性
ECMAScript 2022是新的JS标准 ,将会在2022年的6月份发布。
1、数组中的at()方法
ES2022将会提供从末尾索引类数组对象的能力。
这是一个比较小的特性,但是提高了代码的可读性,当我们在处理arrays 和 strings
At()方法中,当传递正数时,和[]的作用一致;当传递负数的时候,将从末尾往前索引访问值。
用于替换如下写法:
const arr = [1,2,3,4]arr[arr.length - 2] // 3arr.slice(-2)[0] // 3const str = "1234"str[str.length - 2] // '3'str.slice(-2)[0] // '3'
新的写法:
const arr = [1,2,3,4]arr.at(-2) // 3const str = "1234"str.at(-2) // '3'
2、Error Cause
error对象的.cause属性,允许我们明确制定是有哪个错误引发了其他的错误。
看下面的例子:
try {doSomeComputationThatThrowAnError()} catch (error) {throw new Error('I am the result of another error', { cause: error })}
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);
- _**条件渲染模块**_```javascriptconst date = new Date()if(date.getFullYear() === 2023) {await require('/special-code-for-2023-year.js')}
4、私有插槽和方法
自从ES6发布后,Class就出现在原生JS中了,但是相比面向对象的语言,应用场景相对较少。很多的开发者会使用TS的能力由于替代,现在JS提供了原生实现。
私有插槽是其中之一。这个无非就是Class的私有属性。ES2022给与我们创建它们的能力,当我们从CLass的外部访问它们时,就会报错。私有方法也是一样的。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!
完整介绍可以查看:
