ES2025 新特性详解
ECMAScript 2025(ES2025)是JavaScript语言的最新标准版本,带来了多项重要的新特性和改进。以下是主要的新特性概述。
1. 原始类型扩展
BigInt 原生支持
js
// ES2025 中 BigInt 的增强支持
const bigNum = 123n;
console.log(typeof bigNum); // "bigint"
Symbol.prototype.description 属性
js
// 现在可以获取 Symbol 的描述信息
const sym = Symbol('description');
console.log(sym.description); // "description"
2. 数组方法增强
Array.prototype.at()
js
const arr = [1, 2, 3, 4, 5];
console.log(arr.at(0)); // 1 (传统方式: arr[0])
console.log(arr.at(-1)); // 5 (传统方式: arr[arr.length - 1])
console.log(arr.at(-2)); // 4
Array.prototype.toReversed()
js
const arr = [1, 2, 3];
const reversed = arr.toReversed();
console.log(reversed); // [3, 2, 1]
console.log(arr); // [1, 2, 3] (原数组不变)
Array.prototype.toSorted()
js
const arr = [3, 1, 4, 1, 5];
const sorted = arr.toSorted((a, b) => a - b);
console.log(sorted); // [1, 1, 3, 4, 5]
console.log(arr); // [3, 1, 4, 1, 5] (原数组不变)
3. 字符串方法增强
String.prototype.at()
js
const str = "Hello World";
console.log(str.at(0)); // "H"
console.log(str.at(-1)); // "d"
String.prototype.toReversed()
js
const str = "hello";
const reversed = str.toReversed();
console.log(reversed); // "olleh"
4. 对象方法增强
Object.hasOwn()
js
const obj = { name: 'John', age: 30 };
// 更安全的属性检查
console.log(Object.hasOwn(obj, 'name')); // true
console.log(Object.hasOwn(obj, 'toString')); // false (继承属性)
Object.fromEntries() 改进
js
const entries = [['a', 1], ['b', 2]];
const obj = Object.fromEntries(entries);
console.log(obj); // { a: 1, b: 2 }
5. 函数增强
函数参数默认值优化
js
function greet(name = 'World', greeting = 'Hello') {
return `${greeting}, ${name}!`;
}
console.log(greet()); // "Hello, World!"
console.log(greet('Alice')); // "Hello, Alice!"
console.log(greet('Bob', 'Hi')); // "Hi, Bob!"
6. Promise 增强
Promise.allSettled() 的使用
js
const promises = [
Promise.resolve(1),
Promise.reject(new Error('error')),
Promise.resolve(3)
];
Promise.allSettled(promises).then(results => {
results.forEach((result, index) => {
if (result.status === 'fulfilled') {
console.log(`Promise ${index} resolved with:`, result.value);
} else {
console.log(`Promise ${index} rejected with:`, result.reason);
}
});
});
7. 正则表达式增强
Unicode 属性转义
js
// 匹配所有 Unicode 字母
const letterPattern = /\p{Letter}/u;
console.log(letterPattern.test('A')); // true
console.log(letterPattern.test('中')); // true
// 匹配数字
const digitPattern = /\p{Number}/u;
console.log(digitPattern.test('5')); // true
8. 模块系统增强
动态导入增强
js
// 更灵活的动态导入
async function loadModule(modulePath) {
const module = await import(modulePath);
return module.default || module;
}
// 使用示例
loadModule('./utils.js').then(utils => {
utils.doSomething();
});
9. 类和继承增强
私有字段和方法
js
class MyClass {
#privateField = 'private';
#privateMethod() {
return 'private method called';
}
publicMethod() {
return this.#privateField + ' ' + this.#privateMethod();
}
}
const instance = new MyClass();
console.log(instance.publicMethod()); // "private private method called"
10. 实用工具增强
严格模式下的改进
js
'use strict';
// 更严格的错误处理
function strictFunction() {
// 在严格模式下,某些操作会抛出错误
// 如:删除变量、重复参数等
}
11. 性能优化
更好的内存管理
js
// JavaScript 引擎现在有更好的垃圾回收机制
// 例如:更快的 WeakMap 和 WeakSet 处理
const weakMap = new WeakMap();
const obj = {};
weakMap.set(obj, 'value');
// 当 obj 被垃圾回收时,weakMap 中的条目也会自动清除
12. 实际应用示例
综合使用多个新特性
js
// 使用现代 JavaScript 特性创建一个实用工具类
class DataProcessor {
static processData(data) {
// 使用 Array.prototype.at() 和 toReversed()
const lastItem = data.at(-1);
const reversed = data.toReversed();
// 使用 Object.hasOwn() 安全检查属性
const hasName = Object.hasOwn(lastItem, 'name');
// 使用字符串方法
const processed = reversed.map(item =>
typeof item === 'string' ? item.toReversed() : item
);
return {
original: data,
processed,
lastItem,
hasName
};
}
}
// 使用示例
const data = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 },
'hello'
];
const result = DataProcessor.processData(data);
console.log(result);
兼容性考虑
浏览器支持情况
js
// 检查浏览器支持情况
if (typeof Array.prototype.at === 'function') {
console.log('Array.at() is supported');
} else {
console.log('Array.at() is not supported');
}
// polyfill 示例
if (!Array.prototype.at) {
Array.prototype.at = function(index) {
const arr = this;
const len = arr.length;
const actualIndex = index < 0 ? len + index : index;
return arr[actualIndex];
};
}
小结
ES2025 主要增强了:
-
数组和字符串方法:添加了更多实用的不可变方法
-
对象操作:提供了更安全的属性检查方法
-
正则表达式:增强了 Unicode 支持
-
模块系统:改善了动态导入体验
-
性能优化:提升了引擎性能和内存管理
这些新特性使 JavaScript 开发更加现代化、安全和高效。建议在项目中逐步采用这些新特性以提升代码质量。