前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >ES 13 带来了什么

ES 13 带来了什么

原创
作者头像
jadeCarver
发布2022-08-07 09:58:15
5210
发布2022-08-07 09:58:15
举报
文章被收录于专栏:CS成长之路

6月底,ECMAScript的第十三个版本正式发布。

主要新特性概览

  1. top-level await
  2. class new field
  3. Object.hasOwn(obj, propKey)
  4. Method .at() of indexable values
  5. error.cause
  6. RegExp match indices

top-level await

支持在模块顶级直接使用 await,无需 async。直接看例子。

一些应用场景

  • 动态加载模块
代码语言:javascript
复制
const params =new URLSearchParams(location.search);
const language = params.get('lang');
const messages = await import(`./messages-${language}.mjs`); 
// console.log(messages.welcome);
  • 加载备用资源
代码语言:javascript
复制
let lodash;
try {
  lodash = await import('<https://primary.example.com/lodash>');
} catch {
  lodash = await import('<https://secondary.example.com/lodash>');
}
  • 尽快加载
代码语言:javascript
复制
const resource = await Promise.any([
  fetch('<http://example.com/first.txt>')
    .then(response=> response.text()),
	fetch('<http://example.com/second.txt>')
    .then(response=> response.text()),
]);

class 新成员

本次 class 在静态和实例级别支持了多种 field。

公共字段

代码语言:javascript
复制
const computedFieldKey = Symbol("computedFieldKey");
class Something {
  publicField = "a";
  publicFieldThis = this;
  "quoted key" = 1;
  [computedFieldKey] = 2;
}

const instance = new Something();
console.log("publicField", instance.publicField);
console.log("this", instance === instance.publicFieldThis);
console.log("quoted", instance["quoted key"]);
console.log("computed", instance[computedFieldKey]);

结合上面的代码,以下几个点值得注意:

  • field name 支持引号和计算属性值;
  • this 指向最近创建的实例

其中,实例字段的挂载时机遵循以下的原则:

代码语言:javascript
复制
// 初始化时机
class SuperClass {
  superProp = console.log("superProp");
  constructor() {
    console.log("super-constructor");
  }
}
class SubClass extends SuperClass {
  subProp = console.log("subProp");
  constructor() {
    console.log("BEFORE super()");
    super();
    console.log("AFTER super()");
  }
}
new SubClass();
  • 有super,先初始化super调用后super中的字段,之后马上初始化自己的public fields
  • 无super,在 constructor 之前马上被初始化
  • static public fields(静态公共字段) 静态公共字段与实例公共字段类似,同样支持引号和计算属性值,可以写demo来体验。

私有字段和方法

本次新版本支持了class的私有字段定义。之前版本中,为了达到私有,有哪些办法:

  • 在 es6之前,使用短下划线作为约定,但不是真正的私有
  • es6之后,使用 weakMap 实现,但属于一个较为tricky的方式。

在新版中,我们可以使用 # 来标识私有字段。所谓私有字段,则是不允许 class 外部访问。看例子:

代码语言:javascript
复制
// private instance filed
class InstPrivateClass {
  #privateField1 = "private field 1"; // (A)
  #privateField2; // (B) required!
  constructor(value) {
    this.#privateField2 = value; // (C)
  }
  /**
   * Private fields are not accessible outside the class body.
   */
}

const privateIns = new InstPrivateClass();
console.log("private access", privateIns.#privateField1); // error

除此之外,还支持了**private static field(私有静态字段)**,只需要在前面使用 static 标识

值得注意的一点是,私有字段无法被 JSON.stringify 序列化,序列化时,会跳过私有字段。

同时,对于实例来说,我们可以通过设置 filed 和constructor构造函数来初始化。同样的,static的字段除了直接通过 field 来声明,还可以在static block中集中声明:

代码语言:javascript
复制
class C {
  static {
    // statements
  }
}

标准中与typescript中的私有字段有何区别呢?其实很简单,typescript中为编译时的检查,在运行时会被简单地去掉。但 js 规范中会被强制执行,无法运行。

Object.hasOwn(obj, propKey)

这个方法为 hasOwnProperty 的替代品。

eg:

**Object**.hasOwn(obj, 'protoProp')

Method .at() of indexable values

此 API 用来获取指定位置的单个元素,与[index] 索引直接访问不同的是,前者支持负值访问。

适用于 Array、String、TypedArray

eg:

['a', 'b', 'c'].at(0)

['a', 'b', 'c'].at(-1)

error.cause

Error 对象支持指定告警原因。

eg:

代码语言:javascript
复制
try {
	// ···      
} catch (error) {
	throw new Error(`While processing ${filePath}`, { cause: error });
}

RegExp match indices

正则表达式支持指定 /d flag,可以记录捕获组的开始和结束索引。可以通过索引直接访问捕获结果。

同时,捕获结果拥有一个属性 indices 可以获得第 n 个组的开始和结束索引。记录的值是一个左闭右开的区间。

代码语言:javascript
复制
const matchObj = /(a+)(b+)/d.exec("aaaabb");
console.log(matchObj[1]);
console.log(matchObj[2]);
console.log(matchObj.indices[1]); // [0, 4]
console.log(matchObj.indices[2]); // [4, 6]

对于命名捕获组,可以这样访问:

代码语言:javascript
复制
const matchObj = /(?<as>a+)(?<bs>b+)/d.exec('aaaabb');
console.log(matchObj.groups.as);
console.log(matchObj.groups.bs);

他们的索引位置存储在 matchObj.indices.groups

matchObj.indices.groups.as

对于正则本身,暴露一个方法 hasIndices 来判断该表达式是否有 /d

/(?<as>a+)(?<bs>b+)/d.hasIndices

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 6月底,ECMAScript的第十三个版本正式发布。
    • 主要新特性概览
      • top-level await
      • class 新成员
      • Object.hasOwn(obj, propKey)
      • Method .at() of indexable values
      • error.cause
      • RegExp match indices
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档