分分钟带你了解 ES2022 最重要的 4 个特性!

3,579 阅读2分钟

「这是我参与2022首次更文挑战的第22天,活动详情查看:2022首次更文挑战


ECMAScript 2022 将于今年 6 月发布,本篇带来 ES2022 肯定会出现的最重要的 4 个变化!因为这些特性已经进入了 TC39 标准化发布的 第 4 个阶段 了。

TC39 所属于 Ecma International,是一个由 JavaScript 开发者、实现者、学者等组成的团体,与 JavaScript 社区合作维护和发展 JavaScript 的标准。

闲言少叙,冲鸭~~

at() 方法

终于!ES2022 数组新增一个 at() 方法,用于根据索引去取值;

var a = [1, 2, 3]; 

a.at(1) // 2 

a.at(-1) // 3

我们可以通过 a.at(-1) 拿到倒数第一项;

而在这之前,拿数组/字符串最后一项是这样的:

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'

虽然这是一个小的功能改动,但是很大的提高了 数组/字符串 核心操作的可读性;

Error cause

🎉Error cause 是第一个由中国公司(阿里巴巴 TC39 代表 legendecas)代表主导推动的 JavaScript 达到 stage 4 的新特性提案!

这个提案简单理解就是:对 Error 的来源进行一次再包装;

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

Error Constructor 新增了一个可选的参数 options,其中可以设置 cause 并且接受任意 JavaScript 值,把这个值赋值到新创建的 error.cause 上。

try {
  return await fetch('//unintelligible-url-a') // 抛出一个 low level 错误
    .catch(err => {
      throw new Error('Download raw resource failed', { cause: err }) // 将 low level 错误包装成一个 high level、易懂的错误
    })
} catch (err) {
  console.log(err)
  console.log('Caused by', err.cause)
  // Error: Download raw resource failed
  // Caused by TypeError: Failed to fetch
}

顶层 await

顶层 await 允许开发者在 async 函数外部使用 await 字段。

以前:

await Promise.resolve(console.log('🎉'));
// → SyntaxError: await is only valid in async function

(async function () {
  await Promise.resolve(console.log('🎉'));
  // → 🎉
})();

ES2022:

顶层 await 能在模块 modules 的顶层正常工作。(在 class 代码块或非 async 函数仍不支持。)

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')
}

了解更多

私有属性和方法

的概念虽然在 ES6 就被提出,但是它的开发程度远低于面向对象语言,有些新的特性将加入 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!

OK,以上,便是本篇分享~~ 足够简明扼要吧~~

a930a5381a110a0d09118ea234439f40.gif

我是掘金安东尼,输出暴露输入,技术洞见生活,再会~