ECMAScript 2022 现已获得 ECMA International 的批准。ECMAScript 是标准化的 JavaScript 语言,于 1997 年发布了第一版,现已发展成为世界上使用最广泛的通用编程语言之一。
本 Ecma 标准定义了 ECMAScript 2022 Language,是 ECMAScript 语言规范的第 13 版。
ECMAScript 2022 主要包含内容有:
- 引入了 top-level
await
,允许在模块的顶层使用关键字;
// awaiting.mjs import { process } from "./some-module.mjs"; const dynamic = import(computedModuleSpecifier); const data = fetch(url); export const output = process((await dynamic).default, await data);
// usage.mjs import { output } from "./awaiting.mjs"; export function outputPlusValue(value) { return output + value } console.log(outputPlusValue(100)); setTimeout(() => console.log(outputPlusValue(100), 1000);
- 新的 class elements:公共和私有实例字段、公共和私有静态字段、私有实例方法和访问器以及私有静态方法和访问器;
- 类内的静态块,用于执行每个类的评估初始化;
#x in obj
语法,用于测试对象上是否存在私有字段;
class X { #foo; method() { console.log(this.#foo) } }
- 通过
/d
flag 的正则表达式匹配索引,为匹配的子字符串提供开始和结束索引;
const re1 = /a+(?<Z>z)?/d; // indices are relative to start of the input string: const s1 = "xaaaz"; const m1 = re1.exec(s1); m1.indices[0][0] === 1; m1.indices[0][1] === 5; s1.slice(...m1.indices[0]) === "aaaz"; m1.indices[1][0] === 4; m1.indices[1][1] === 5; s1.slice(...m1.indices[1]) === "z"; m1.indices.groups["Z"][0] === 4; m1.indices.groups["Z"][1] === 5; s1.slice(...m1.indices.groups["Z"]) === "z"; // capture groups that are not matched return `undefined`: const m2 = re1.exec("xaaay"); m2.indices[1] === undefined; m2.indices.groups["Z"] === undefined;
Error
对象的cause
属性,可用于记录错误的因果链;
async function doJob() { const rawResource = await fetch('//domain/resource-a') .catch(err => { throw new Error('Download raw resource failed', { cause: err }); }); const jobResult = doComputationalHeavyJob(rawResource); await fetch('//domain/upload', { method: 'POST', body: jobResult }) .catch(err => { throw new Error('Upload job result failed', { cause: err }); }); } try { await doJob(); } catch (e) { console.log(e); console.log('Caused by', e.cause); } // Error: Upload job result failed // Caused by TypeError: Failed to fetch
- Strings、Arrays 和 TypedArrays 的
at
方法,允许相对索引;
function at(n) { // ToInteger() abstract op n = Math.trunc(n) || 0; // Allow negative indexing from the end if (n < 0) n += this.length; // OOB access is guaranteed to return undefined if (n < 0 || n >= this.length) return undefined; // Otherwise, this is just normal property access return this[n]; } const TypedArray = Reflect.getPrototypeOf(Int8Array); for (const C of [Array, String, TypedArray]) { Object.defineProperty(C.prototype, "at", { value: at, writable: true, enumerable: false, configurable: true }); }
- 以及
Object.hasOwn
,这是Object.prototype.hasOwnProperty
的一个更简洁方便的替代方法。
let hasOwnProperty = Object.prototype.hasOwnProperty if (hasOwnProperty.call(object, "foo")) { console.log("has property foo") }
简化为:
if (Object.hasOwn(object, "foo")) { console.log("has property foo") }
具体可查看:
- https://262.ecma-international.org/13.0/index.html
- https://www.ecma-international.org/wp-content/uploads/ECMA-262_13th_edition_june_2022.pdf