
ES13 (ES2022)新特性
文章类型:Javascript
发布者:hp
发布时间:2025-03-10
1:类的公共字段和私有字段:支持在类中定义实例字段。并通过#前缀定义私有字段/方法
class User {
#secretKey = '123'; // 私有字段
name = '匿名'; // 公有字段
static #count = 0; // 静态私有字段
}
const user = new User();
console.log(user.#secretKey); // 报错:私有字段不可访问
2:顶层 await (Top-Level Await):在模块的顶层使用 await。
// 直接加载模块依赖
const data = await fetch('https://api.example.com/data');
export default data;
3:改进正则表达式匹配:通过 hasIndices 标记来获取匹配索引信息。
const regex = /a+(b+)/d;
const str = 'aaabbb';
const result = regex.exec(str);
console.log(result.indices);
// 输出: [[0, 6], [3, 6]] (外层数组为完整匹配索引,内层数组为捕获组索引)
4:静态类块(Static Blocks):在类内部通过 static {} 块执行静态初始化逻辑
class Config {
static API_URL;
static {
this.API_URL = process.env.API_URL || 'default';
}
}
5:数组索引.at()方法:通过正/负索引直接访问数组元素(如 arr.at(-1) 获取末位元素)
const arr = [10, 20, 30];
console.log(arr.at(-1)); // 输出: 30 ==**:ml-citation{ref="1" data="citationList"}**==
6:Ergonomic 品牌检查(#x in obj):通过 #x in obj 语法检查对象是否包含指定私有字段
class Secure {
#key;
static hasKey(obj) {
return #key in obj; // 检查私有字段存在性
}
}
1:优先采用:顶级 await 简化异步模块加载逻辑
2:避免滥用:私有字段需谨慎设计,防止过度封装
3:性能优化:.at() 方法提升数组操作的语义清晰度