ECMAScript 2022正式发布
全栈前端精选
共 3290字,需浏览 7分钟
·
2022-07-05 18:57
引入了 top-level
await
,允许在模块的顶层使用关键字;
// 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:公共和私有实例字段、公共和私有静态字段、私有实例方法和访问器以及私有静态方法和访问器;
类内的静态块,用于执行每个类的评估初始化;
#x in obj
语法,用于测试对象上是否存在私有字段;
classX{
#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 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
评论