no-new

禁止在赋值或比较之外使用 new 运算符

new 与构造函数一起使用的目标通常是创建特定类型的对象并将该对象存储在变量中,例如:

¥The goal of using new with a constructor is typically to create an object of a particular type and store that object in a variable, such as:

var person = new Person();

使用 new 而不存储结果的情况不太常见,例如:

¥It’s less common to use new and not store the result, such as:

new Person();

在这种情况下,创建的对象被丢弃,因为它的引用没有存储在任何地方,并且在许多情况下,这意味着构造函数应该替换为不需要使用 new 的函数。

¥In this case, the created object is thrown away because its reference isn’t stored anywhere, and in many cases, this means that the constructor should be replaced with a function that doesn’t require new to be used.

规则详情

¥Rule Details

此规则旨在通过禁止使用不将结果对象分配给变量的 new 关键字的构造函数调用来保持一致性和约定。

¥This rule is aimed at maintaining consistency and convention by disallowing constructor calls using the new keyword that do not assign the resulting object to a variable.

此规则的错误代码示例:

¥Examples of incorrect code for this rule:

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

new Thing();

此规则的正确代码示例:

¥Examples of correct code for this rule:

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

var thing = new Thing();

Foo();

版本

此规则是在 ESLint v0.0.7 中引入。

资源

ESLint 中文网
粤ICP备13048890号