unicorn/new-for-builtins 严格
作用
强制对以下内置构造函数使用 new:Object、Array、ArrayBuffer、BigInt64Array、BigUint64Array、DataView、Date、Error、Float32Array、Float64Array、Function、Int8Array、Int16Array、Int32Array、Map、WeakMap、Set、WeakSet、Promise、RegExp、Uint8Array、Uint16Array、Uint32Array、Uint8ClampedArray、SharedArrayBuffer、Proxy、WeakRef、FinalizationRegistry。
禁止对以下内置构造函数使用 new:String、Number、Boolean、Symbol、BigInt。
为什么这是不好的?
不一致地使用 new 可能导致混淆。像 Array 和 RegExp 这样的构造函数应始终使用 new,以确保获得预期的实例类型。而 String、Number、Boolean、Symbol 和 BigInt 不应使用 new,因为它们会创建对象包装器,而不是原始值。
示例
此规则的 错误 代码示例:
javascript
const foo = new String("hello world");
const bar = Array(1, 2, 3);此规则的 正确 代码示例:
javascript
const foo = String("hello world");
const bar = new Array(1, 2, 3);如何使用
通过配置文件或 CLI 启用此规则,可以使用:
json
{
"rules": {
"unicorn/new-for-builtins": "error"
}
}bash
oxlint --deny unicorn/new-for-builtins