ES2021 新特性已获得 ECMA 组织正式认可!(速览)

主要有几个新特性:

Logical Assignment Operators (逻辑分配运算符)

//"Or Or Equals"
x ||= y;
x || (y = z);

// "And And Equals"
x &&= y;
x && (y = z);

// "QQ Equals"
x ??= y;
x ?? (y = z);

以前的代码可以写的更加简洁:

// We can do this
if (!user.id) user.id = 1
// Or this
user.id = user.id || 1

// Or use logical assignment operator.
user.id ||= 1

Numeric Separators(数值分割符)

可以使用_分割数值,可读性更好

1_000_000_000           // Ah, so a billion
101_475_938.38          // And this is hundreds of millions

let fee = 123_00;       // $123 (12300 cents, apparently)
let fee = 12_300;       // $12,300 (woah, that fee!)
let amount = 12345_00;  // 12,345 (1234500 cents, apparently)
let amount = 123_4500;  // 123.45 (4-fixed financial)
let amount = 1_234_500; // 1,234,500

Promise.any and AggregateError

在所有请求都出错时才被 rejected

Promise.any([
  fetch('https://v8.dev/').then(() => 'home'),
  fetch('https://v8.dev/blog').then(() => 'blog'),
  fetch('https://v8.dev/docs').then(() => 'docs')
]).then(
  (first) => {
    // Any of the promises was fulfilled.
  },
  (error) => {
    // All of the promises were rejected.
  }
);

String.prototype.replaceAll

增加 String 新方法 replaceAll

'xxx'.replaceAll('', '_');
// → '_x_x_x_'

WeakRefs and FinalizationRegistry Objects

增加 WeakRefsFinalizationRegistry 对象:

let target = {};
let wr = new WeakRef(target);

//wr and target aren't the same

// Creating a new registry
const registry = new FinalizationRegistry(heldValue => {
  // ....
});

registry.register(myObject, "some value", myObject);
// ...some time later, if you don't care about `myObject` anymore...
registry.unregister(myObject);

FinalizationRegistry 不懂的同学可以看下:MDN FinalizationRegistry。这两个主要用了做内存管理,日常开发应该比较少见,规范可见:managing-memory

详见:ecma262

javascript
413 views
Comments
登录后评论
Sign In
·

WeakRef 相比 WeekMap 提供了真正的弱引用,WeakRef 实例有一个方法 deref,该方法返回被引用的原始对象,如果原始对象已被收集,则返回 undefined 对象。

let target = {};
let wr = new WeakRef(target);
const obj = wr.deref(); // 使用是需要判断是否为 undefined
·

写过很多代码,只见过一次 WeakMap 使用,是在 slate.js 里面,当时好奇怎么可以根据对象获取到 KV 值,对象销毁了怎么办?点进去就是一个 WeakMap,算是一个技巧吧,在不想增加对象属性的时候为对象增加附加值的方法