no-new-native-nonconstructor
禁止具有全局非构造函数的 new 运算符
在 配置文件 中使用来自 @eslint/js 的 recommended 配置可以启用此规则
在 JavaScript 中,有一个约定是以大写字母开头的全局变量通常表示可以使用 new 操作符实例化的类,例如 new Array 和 new Map。令人困惑的是,JavaScript 也提供了一些以大写字母开头的全局变量,这些变量不能使用 new 操作符调用,如果尝试这样做会抛出错误。它们通常是与数据类型相关的函数,很容易被误认为是类。请考虑以下例子:
🌐 It is a convention in JavaScript that global variables beginning with an uppercase letter typically represent classes that can be instantiated using the new operator, such as new Array and new Map. Confusingly, JavaScript also provides some global variables that begin with an uppercase letter that cannot be called using the new operator and will throw an error if you attempt to do so. These are typically functions that are related to data types and are easy to mistake for classes. Consider the following example:
// throws a TypeError
const foo = new Symbol("foo");
// throws a TypeError
const result = new BigInt(9007199254740991);
new Symbol 和 new BigInt 都会抛出类型错误,因为它们是函数而不是类。很容易犯这个错误,因为人们会假设大写字母表示的是类。
🌐 Both new Symbol and new BigInt throw a type error because they are functions and not classes. It is easy to make this mistake by assuming the uppercase letters indicate classes.
规则详情
🌐 Rule Details
此规则旨在防止使用 new 操作符意外调用原生 JavaScript 全局函数。这些函数包括:
🌐 This rule is aimed at preventing the accidental calling of native JavaScript global functions with the new operator. These functions are:
SymbolBigInt
此规则的错误代码示例:
🌐 Examples of incorrect code for this rule:
/*eslint no-new-native-nonconstructor: "error"*/
const foo = new Symbol('foo');
const bar = new BigInt(9007199254740991);
符合此规则的正确代码示例:
🌐 Examples of correct code for this rule:
/*eslint no-new-native-nonconstructor: "error"*/
const foo = Symbol('foo');
const bar = BigInt(9007199254740991);
// Ignores shadowed Symbol.
function baz(Symbol) {
const qux = new Symbol("baz");
}
function quux(BigInt) {
const corge = new BigInt(9007199254740991);
}
选项
🌐 Options
此规则没有选项。
🌐 This rule has no options.
何时不使用
🌐 When Not To Use It
此规则不应在 ES3/5 环境中使用。
🌐 This rule should not be used in ES3/5 environments.
由 TypeScript 处理
使用 TypeScript 时禁用此规则是安全的,因为 TypeScript 的编译器强制执行此检查。
相关规则
版本
此规则是在 ESLint v8.27.0 中引入。