IT资讯 ECMAScript 2021 特性预览

oswald · 2021-02-04 09:30:06 · 热度: 14

最新举行的一次 TC39 会议正式确定了 ECMAScript 2021 的完整功能列表。具体包含以下内容:

String.prototype.replaceAll

此前,如果想要替换所有的 string occurrences,则需要使用 String.prototype.replace 和全局 regexp 的组合。现在,String.prototype.replaceAll简化了这一点。

const string = "it-is-just-a-test";

// instead of doing this
string.replace(/-/g, "_")
// "it_is_just_a_test"

// in ES2021 we can do
string.replaceAll("-", "_")
// "it_is_just_a_test"

Promise.any

将 Promise.any 加入了 2021 年规范中的 Promise combinators 列表。当你想处理第一个 fulfills 的 Promise 时,可以使用 Promise.any。与 Promise.race 不同,当其中一个 promises fail 时,它不会 reject。更多详情可查看“Promise combinators explained”。 

const API = "https://api.github.com/users"

Promise.any([
  fetch(`${API}/pawelgrzybek`),
  fetch(`${API}/gabriel403`)
])
  .then(response => response.json())
  .then(({name}) => console.log(`Cool dude is: ${name}`))
  .catch(error => console.error(error));

ECMAScript 2021 特性预览

WeakRefs

WeakRefs 提案为语言带来了两个新的 contructors:WeakRef 和 FinalizationRegistry。这些新功能是更复杂、更低级的语言概念。

WeakRef

当将一个对象分配给一个变量时,它指向存储这个对象的值的那块内存(强引用)。如果程序不再引用这个对象,garbage collector 会销毁它并回收内存。WeakRef 的一个实例创建了一个对给定对象的引用,如果该对象仍然在内存中,则返回该对象;如果目标对象已经被垃圾回收,则返回未定义的对象。

const obj = { spec: "ES2021" };
const objWeakRef = new WeakRef(obj);

// do something cool

objWeakRef.deref();
// returns obj in case it is still in memory
// returns undefined in case it has been garbage collected

FinalizationRegistry

FinalizationRegistry 的实例在注册的目标对象被垃圾收集后触发回调函数。

const obj = { spec: "ES2021" }; const registry = new FinalizationRegistry(value => { console.log(`The ${value} object has been garbage collected.`) }); registry.register(obj, "ECMAScript 2021"); // perform some action that triggers garbage collector on obj // The ECMAScript 2021 object has been garbage collected. 

值得注意的是,官方提示要尽量避免使用 WeakRef 和 FinalizationRegistry,垃圾回收机制依赖于 JavaScript 引擎的实现,不同的引擎或是不同版本的引擎可能会有所不同。

Logical Assignment Operators

顾名思义,逻辑赋值运算符是逻辑运算符(&&, || and ??)和赋值运算符(=)的组合。

// set a to b only when a is truthy
a &&= b;
// set a to b only when a is falsy
a ||= b;
// set a to b only when a is nullish
a ??= b;

Numeric separators

数字的可读性随着数字长度的增加而降低。现在,则可以使用下划线(_, U+005F)来分隔数字组,使得长数字更加清晰可读。这个功能在 JavaPythonPerlRuby 、Rust、Julia、Ada、C# 等其他编程语言中也很有名。

const population = 37_653_260

 详情可查看:https://pawelgrzybek.com/whats-new-in-ecmascript-2021/

猜你喜欢:
暂无回复。
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册