ECMAScript 2022正式發(fā)布
引入了 top-level
await,允許在模塊的頂層使用關(guān)鍵字;
// awaiting.mjsimport { process } from "./some-module.mjs";const dynamic = import(computedModuleSpecifier);const data = fetch(url);export const output = process((await dynamic).default, await data);
// usage.mjsimport { output } from "./awaiting.mjs";export functionoutputPlusValue(value) { return output + value }console.log(outputPlusValue(100));setTimeout(() => console.log(outputPlusValue(100), 1000);
新的 class elements:公共和私有實例字段、公共和私有靜態(tài)字段、私有實例方法和訪問器以及私有靜態(tài)方法和訪問器;
類內(nèi)的靜態(tài)塊,用于執(zhí)行每個類的評估初始化;
#x in obj語法,用于測試對象上是否存在私有字段;
classX{
#foo;
method() {
console.log(this.#foo)
}}
通過
/dflag 的正則表達式匹配索引,為匹配的子字符串提供開始和結(jié)束索引;
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 functiondoJob() {
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方法,允許相對索引;
functionat(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.hasOwnPropertyif (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
評論
圖片
表情
