ECMAScript 2022(ES13)
2025-02-20 20:00
2025-02-23 09:20
核心特性
1. 类的私有字段与私有方法(# 前缀)
通过 # 定义类内部私有成员,外部无法直接访问,用于封装敏感数据或内部逻辑。
class User {
#password; // 私有字段
constructor(name, password) {
this.name = name;
this.#password = password;
}
#validate() {
// 私有方法
return this.#password.length >= 8;
}
}
const user = new User("xlei", "12345678");
console.log(user.#password); // 报错:私有字段不可访问
2. 顶级 await
在模块顶层直接使用 await,无需包裹在 async 函数中。
// 动态导入模块并初始化
const data = await fetch("/config.json").then(res => res.json());
export const config = data;
3. 正则表达式匹配索引(/d 标志)
通过 indices 属性获取匹配的起始和结束索引。
const regex = /a+(?<groupName>b)?/d;
const match = regex.exec("aaab");
console.log(match.indices[0]); // [0, 4](整个匹配的索引)
console.log(match.indices.groups.groupName); // [3, 4](命名捕获组索引)
4. Error.prototype.cause
允许在错误对象中链式传递根本原因。
try {
throw new Error("DB连接失败", { cause: "网络超时" });
} catch (err) {
throw new Error("服务不可用", { cause: err });
}
5. .at()
支持数组、字符串的负索引访问(如 arr.at(-1) 获取最后一个元素)。
const arr = [1, 2, 3];
console.log(arr.at(-1)); // 3
const str = "Hello";
console.log(str.at(-2)); // 'l'
6. Object.hasOwn()
替代 Object.prototype.hasOwnProperty.call,更简洁地检测对象自身属性。
const obj = { a: 1 };
console.log(Object.hasOwn(obj, "a")); // true
console.log(Object.hasOwn(obj, "toString")); // false(继承属性)
总结
ECMAScript 2022(ES13) 通过 私有字段 和 静态类块 强化了类的封装性,Top-level await 简化了模块初始化流程,.at() 和 Object.hasOwn() 提升了数据操作的便捷性。其特性广泛应用于模块化架构、安全数据管理及复杂错误处理场景,进一步推动了 JavaScript 在大型应用中的工程化能力。后续版本(如 ES2023 的 findLast 数组方法)延续了对数据处理的精细化支持。
评论区
评论区寄了
文章目录
核心特性
1. 类的私有字段与私有方法(# 前缀)
2. 顶级 await
3. 正则表达式匹配索引(/d 标志)
4. Error.prototype.cause
5. .at()
6. Object.hasOwn()
总结