ES11来了,还学得动吗?

写在前面

ES2020(即 ES11)上周(2020 年 6 月)已经正式发布,在此以前进入 Stage 4 的 10 项提案均已归入规范,成为 JavaScript 语言的新特性html

一.特性一览

ES Module 迎来了一些加强:前端

正式支持了安全的链式操做:git

提供了大数运算的原生支持:es6

一些基础 API 也有了新的变化:github

  • Promise.allSettled:一个新的 Promise 组合器,不像allrace同样具备短路特性
  • String.prototype.matchAll:以迭代器的形式返回全局匹配模式下的正则表达式匹配到的全部结果(indexgroups等)
  • globalThis:访问全局做用域this的通用方法
  • for-in mechanics:规范for-in循环的某些行为

二.ES Module 加强

动态 import

咱们知道ES Module是一套静态的模块系统正则表达式

The existing syntactic forms for importing modules are static declarations.

静态体如今:数组

They accept a string literal as the module specifier, and introduce bindings into the local scope via a pre-runtime "linking" process.
  • 静态加载:import/export声明只能出如今顶层做用域,不支持按需加载、懒加载
  • 静态标识:模块标识只能是字符串字面量,不支持运行时动态计算而来的模块名

例如:promise

if (Math.random()) {
    import 'foo'; // SyntaxError
}

// You can’t even nest `import` and `export`
// inside a simple block:
{
    import 'foo'; // SyntaxError
}

这种严格的静态模块机制让基于源码的静态分析、编译优化有了更大的发挥空间:浏览器

This is a great design for the 90% case, and supports important use cases such as static analysis, bundling tools, and tree shaking.

但对另外一些场景很不友好,好比:安全

  • 苛求首屏性能的场景:经过import声明引用的全部模块(包括初始化暂时用不到的模块)都会在初始化阶段前置加载,影响首屏性能
  • 难以提早肯定目标模块标识的场景:例如根据用户的语言选项动态加载不一样的模块(module-enmodule-zh等)
  • 仅在特殊状况下才须要加载某些模块的场景:例如异常状况下加载降级模块

为了知足这些须要动态加载模块的场景,ES2020 推出了动态 import 特性(import()):

import(specifier)

import()“函数”输入模块标识specifier(其解析规则与import声明相同),输出Promise,例如:

// 目标模块  ./lib/my-math.js
function times(a, b) {
  return a * b;
}
export function square(x) {
  return times(x, x);
}
export const LIGHTSPEED = 299792458;

// 当前模块 index.js
const dir = './lib/';
const moduleSpecifier = dir + 'my-math.mjs';

async function loadConstant() {
  const myMath = await import(moduleSpecifier);
  const result = myMath.LIGHTSPEED;
  assert.equal(result, 299792458);
  return result;
}
// 或者不用 async & await
function loadConstant() {
  return import(moduleSpecifier)
  .then(myMath => {
    const result = myMath.LIGHTSPEED;
    assert.equal(result, 299792458);
    return result;
  });
}

import声明相比,import()特色以下:

  • 可以在函数、分支等非顶层做用域使用,按需加载、懒加载都不是问题
  • 模块标识支持变量传入,可动态计算肯定模块标识
  • 不只限于module,在普通的script中也能使用

注意,虽然长的像函数,但import()其实是个操做符,由于操做符可以携带当前模块相关信息(用来解析模块表示),而函数不能:

Even though it works much like a function, import() is an operator: in order to resolve module specifiers relatively to the current module, it needs to know from which module it is invoked. A normal function cannot receive this information as implicitly as an operator can. It would need, for example, a parameter.

import.meta

另外一个 ES Module 新特性是import.meta,用来透出模块特定的元信息:

import.meta, a host-populated object available in Modules that may contain contextual information about the Module.

好比:

  • 模块的 URL 或文件名:例如 Node.js 里的__dirname__filename
  • 所处的script标签:例如浏览器支持的document.currentScript
  • 入口模块:例如 Node.js 里的process.mainModule

诸如此类的元信息均可以挂到import.meta属性上,例如:

// 模块的 URL(浏览器环境)
import.meta.url
// 当前模块所处的 script 标签
import.meta.scriptElement

须要注意的是,规范并无明肯定义具体的属性名和含义,都由具体实现来定,因此特性提案里的但愿浏览器支持的这两个属性未来可能支持也可能不支持

P.S.import.meta自己是个对象,原型为null

export-ns-from

第三个 ES Module 相关的新特性是另外一种模块导出语法:

export * as ns from "mod";

同属于export ... from ...形式的聚合导出,做用上相似于:

import * as ns from "mod";
export {ns};

但不会在当前模块做用域引入目标模块的各个 API 变量

P.S.对照import * as ns from "mod";语法,看起来像是 ES6 模块设计中排列组合的一个疏漏;)

三.链式操做支持

Optional Chaining

至关实用的一个特性,用来替代诸如此类冗长的安全链式操做:

const street = user && user.address && user.address.street;

可换用新特性(?.):

const street = user?.address?.street;

语法格式以下:

obj?.prop     // 访问可选的静态属性
// 等价于
(obj !== undefined && obj !== null) ? obj.prop : undefined

obj?.[«expr»] // 访问可选的动态属性
// 等价于
(obj !== undefined && obj !== null) ? obj[«expr»] : undefined

func?.(«arg0», «arg1») // 调用可选的函数或方法
// 等价于
(func !== undefined && func !== null) ? func(arg0, arg1) : undefined

P.S.注意操做符是?.而不是单?,在函数调用中有些奇怪alert?.(),这是为了与三目运算符中的?区分开

机制很是简单,若是出如今问号前的值不是undefinednull,才执行问号后的操做,不然返回undefined

一样具备短路特性:

// 在 .b?.m 时短路返回了 undefined,而不会 alert 'here'
({a: 1})?.a?.b?.m?.(alert('here'))

&&相比,新的?.操做符更适合安全进行链式操做的场景,由于:

  • 语义更明确:?.遇到属性/方法不存在就返回undefined,而不像&&同样返回左侧的值(几乎没什么用)
  • 存在性判断更准确:?.只针对nullundefined,而&&遇到任意假值都会返回,有时没法知足须要

例如经常使用的正则提取目标串,语法描述至关简洁:

'string'.match(/(sing)/)?.[1] // undefined
// 以前须要这样作
('string'.match(/(sing)/) || [])[1] // undefined

还能够配合 Nullish coalescing Operator 特性填充默认值:

'string'.match(/(sing)/)?.[1] ?? '' // ''
// 以前须要这样作
('string'.match(/(sing)/) || [])[1] || '' // ''
// 或者
('string'.match(/(sing)/) || [, ''])[1] // ''

Nullish coalescing Operator

一样引入了一种新的语法结构(??):

actualValue ?? defaultValue
// 等价于
actualValue !== undefined && actualValue !== null ? actualValue : defaultValue

用来提供默认值,当左侧的actualValueundefinednull时,返回右侧的defaultValue,不然返回左侧actualValue

相似于||,主要区别在于??只针对nullundefined,而||遇到任一假值都会返回右侧的默认值

四.大数运算

新增了一种基础类型,叫BigInt,提供大整数运算支持:

BigInt is a new primitive that provides a way to represent whole numbers larger than 2^53, which is the largest number Javascript can reliably represent with the Number primitive.

BigInt

JavaScript 中Number类型所能准确表示的最大整数是2^53,不支持对更大的数进行运算:

const x = Number.MAX_SAFE_INTEGER;
// 9007199254740991 即 2^53 - 1
const y = x + 1;
// 9007199254740992 正确
const z = x + 2
// 9007199254740992 错了,没变

P.S.至于为何是 2 的 53 次方,是由于 JS 中数值都以 64 位浮点数形式存放,刨去 1 个符号位,11 个指数位(科学计数法中的指数),剩余的 52 位用来存放数值,2 的 53 次方对应的这 52 位所有为 0,能表示的下一个数是2^53 + 2,中间的2^53 + 1没法表示:

[caption id="attachment_2213" align="alignnone" width="625"]<img src="http://www.ayqy.net/cms/wordpress/wp-content/uploads/2020/06/JavaScript-Max-Safe-Integer-1024x518.jpg" alt="JavaScript Max Safe Integer" width="625" height="316" class="size-large wp-image-2213" /> JavaScript Max Safe Integer[/caption]

具体解释见BigInts in JavaScript: A case study in TC39

BigInt类型的出现正是为了解决此类问题:

9007199254740991n + 2n
// 9007199254740993n 正确

引入的新东西包括:

  • 大整数字面量:给数字后缀一个n表示大整数,例如9007199254740993n0xFFn(二进制、八进制、十进制、十六进制字面量统统能够后缀个n变成BigInt
  • bigint基础类型:typeof 1n === 'bigint'
  • 类型构造函数:BigInt
  • 重载数学运算符(加减乘除等):支持大整数运算

例如:

// 建立一个 BigInt
9007199254740993n
// 或者
BigInt(9007199254740993)

// 乘法运算
9007199254740993n * 2n
// 幂运算
9007199254740993n ** 2n
// 比较运算
0n === 0  // false
0n === 0n // true
// toString
123n.toString() === '123'

P.S.关于 BigInt API 细节的更多信息,见ECMAScript feature: BigInt – arbitrary precision integers

须要注意的是BigInt不能与Number混用进行运算

9007199254740993n * 2
// 报错 Uncaught TypeError: Cannot mix BigInt and other types, use explicit conversions

而且BigInt只能表示整数,因此除法直接取整(至关于Math.trunc()):

3n / 2n === 1n

五.基础 API

基础 API 也有一些新的变化,包括 Promise、字符串正则匹配、for-in循环等

Promise.allSettled

Promise.allPromise.race以后,Promise新增了一个静态方法叫allSettled

// 传入的全部 promise 都有结果(从 pending 状态变成 fulfilled 或 rejected)以后,触发 onFulfilled
Promise.allSettled([promise1, promise2]).then(onFulfilled);

P.S.另外,any也在路上了,目前(2020/6/21)处于 Stage 3

相似于all,但不会由于某些项rejected而短路,也就是说,allSettled会等到全部项都有结果(不管成功失败)后才进入Promise链的下一环(因此它必定会变成 Fulfilled 状态):

A common use case for this combinator is wanting to take an action after multiple requests have completed, regardless of their success or failure.

例如:

Promise.allSettled([Promise.reject('No way'), Promise.resolve('Here')])
  .then(results => {
    console.log(results);
    // [
    //   {status: "rejected", reason: "No way"},
    //   {status: "fulfilled", value: "Here"}
    // ]
  }, error => {
    // No error can get here!
  })

String.prototype.matchAll

字符串处理的一个常见场景是想要匹配出字符串中的全部目标子串,例如:

const str = 'es2015/es6 es2016/es7 es2020/es11';
str.match(/(es\d+)\/es(\d+)/g)
// 顺利获得 ["es2015/es6", "es2016/es7", "es2020/es11"]

match()方法中,正则表达式所匹配到的多个结果会被打包成数组返回,但没法得知每一个匹配除结果以外的相关信息,好比捕获到的子串,匹配到的index位置等:

This is a bit of a messy way to obtain the desired information on all matches.

此时只能求助于最强大的exec

const str = 'es2015/es6 es2016/es7 es2020/es11';
const reg = /(es\d+)\/es(\d+)/g;
let matched;
let formatted = [];
while (matched = reg.exec(str)) {
  formatted.push(`${matched[1]} alias v${matched[2]}`);
}
console.log(formatted);
// 获得 ["es2015 alias v6", "es2016 alias v7", "es2020 alias v11"]

而 ES2020 新增的matchAll()方法就是针对此类种场景的补充:

const results = 'es2015/es6 es2016/es7 es2020/es11'.matchAll(/(es\d+)\/es(\d+)/g);
// 转数组处理
Array.from(results).map(r => `${r[1]} alias v${r[2]}`);
// 或者从迭代器中取出直接处理
// for (const matched of results) {}
// 获得结果同上

注意,matchAll()不像match()同样返回数组,而是返回一个迭代器,对大数据量的场景更友好

for-in 遍历机制

JavaScript 中经过for-in遍历对象时 key 的顺序是不肯定的,由于规范没有明肯定义,而且可以遍历原型属性让for-in的实现机制变得至关复杂,不一样 JavaScript 引擎有各自根深蒂固的不一样实现,很难统一

因此 ES2020 不要求统一属性遍历顺序,而是对遍历过程当中的一些特殊 Case 明肯定义了一些规则:

  • 遍历不到 Symbol 类型的属性
  • 遍历过程当中,目标对象的属性能被删除,忽略掉还没有遍历到却已经被删掉的属性
  • 遍历过程当中,若是有新增属性,不保证新的属性能被当次遍历处理到
  • 属性名不会重复出现(一个属性名最多出现一次)
  • 目标对象整条原型链上的属性都能遍历到

具体见13.7.5.15 EnumerateObjectProperties

globalThis

最后一个新特性是globalThis,用来解决浏览器,Node.js 等不一样环境下,全局对象名称不统一,获取全局对象比较麻烦的问题:

var getGlobal = function () {
  // the only reliable means to get the global object is
  // `Function('return this')()`
  // However, this causes CSP violations in Chrome apps.
  if (typeof self !== 'undefined') { return self; }
  if (typeof window !== 'undefined') { return window; }
  if (typeof global !== 'undefined') { return global; }
  throw new Error('unable to locate global object');
};

globalThis做为统一的全局对象访问方式,老是指向全局做用域中的this值:

The global variable globalThis is the new standard way of accessing the global object. It got its name from the fact that it has the same value as this in global scope.

P.S.为何不叫global?是由于global可能会影响现有的一些代码,因此另起一个globalThis避免冲突

至此,ES2020 的全部新特性都清楚了

六.总结

比起ES2019,ES2020 算是一波大更新了,动态 import、安全的链式操做、大整数支持……全都加入了豪华午饭

参考资料

有所得、有所惑,真好

关注「前端向后」微信公众号,你将收获一系列「用原创」的高质量技术文章,主题包括但不限于前端、Node.js以及服务端技术

本文首发于 ayqy.net ,原文连接:http://www.ayqy.net/blog/es2020/

相关文章
相关标签/搜索