no-new-native-nonconstructor
禁止具有全局非构造函数的 new
运算符
Disallow new
operators with global non-constructor functions
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
let foo = new Symbol("foo");
// throws a TypeError
let 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.