no-new-native-nonconstructor

禁止具有全局非构造函数的 new 运算符

Recommended

配置文件 中使用来自 @eslint/jsrecommended 配置可以启用此规则

JavaScript 中的约定是,以大写字母开头的全局变量通常表示可以使用 new 运算符实例化的类,例如 new Arraynew 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
let foo = new Symbol("foo");

// throws a TypeError
let result = new BigInt(9007199254740991);

new Symbolnew 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:

  • Symbol

  • BigInt

示例

¥Examples

此规则的错误代码示例:

¥Examples of incorrect code for this rule:

在线运行
/*eslint no-new-native-nonconstructor: "error"*/

var foo = new Symbol('foo');
var bar = new BigInt(9007199254740991);

此规则的正确代码示例:

¥Examples of correct code for this rule:

在线运行
/*eslint no-new-native-nonconstructor: "error"*/

var foo = Symbol('foo');
var bar = BigInt(9007199254740991);

// Ignores shadowed Symbol.
function baz(Symbol) {
    const qux = new Symbol("baz");
}
function quux(BigInt) {
    const corge = new BigInt(9007199254740991);
}

何时不使用

¥When Not To Use It

此规则不应在 ES3/5 环境中使用。

¥This rule should not be used in ES3/5 environments.

由 TypeScript 处理

使用 TypeScript 时禁用此规则是安全的,因为 TypeScript 的编译器强制执行此检查。

版本

此规则是在 ESLint v8.27.0 中引入。

进阶读物

资源

ESLint 中文网
粤ICP备13048890号