no-new-object
禁止 Object
构造函数
该规则在 ESLint v8.50.0 中已弃用,并由 no-object-constructor 规则取代。新规则标记了更多可以使用对象字面量语法的情况,并且当使用参数调用 Object
构造函数时,它不会报告问题。
¥This rule was deprecated in ESLint v8.50.0 and replaced by the no-object-constructor rule. The new rule flags more situations where object literal syntax can be used, and it does not report a problem when the Object
constructor is invoked with an argument.
Object
构造函数用于在 JavaScript 中创建新的泛型对象,例如:
¥The Object
constructor is used to create new generic objects in JavaScript, such as:
var myObject = new Object();
但是,这与使用更简洁的对象字面量语法没有什么不同:
¥However, this is no different from using the more concise object literal syntax:
var myObject = {};
出于这个原因,许多人更喜欢总是使用对象字面量语法,而从不使用 Object
构造函数。
¥For this reason, many prefer to always use the object literal syntax and never use the Object
constructor.
虽然这两种方法之间没有性能差异,但对象字面量形式的字节节省和简洁性使其成为创建新对象的事实上的方式。
¥While there are no performance differences between the two approaches, the byte savings and conciseness of the object literal form is what has made it the de facto way of creating new objects.
规则详情
¥Rule Details
该规则不允许使用 new
调用 Object
构造函数。
¥This rule disallows calling the Object
constructor with new
.
此规则的错误代码示例:
¥Examples of incorrect code for this rule:
/*eslint no-new-object: "error"*/
var myObject = new Object();
new Object();
var foo = new Object("foo");
此规则的正确代码示例:
¥Examples of correct code for this rule:
/*eslint no-new-object: "error"*/
var myObject = new CustomObject();
var myObject = {};
var Object = function Object() {};
new Object();
var foo = Object("foo");
何时不使用
¥When Not To Use It
如果你希望允许 Object
构造函数与 new
一起使用,你可以安全地关闭此规则。
¥If you wish to allow the use of the Object
constructor with new
, you can safely turn this rule off.
相关规则
版本
此规则是在 ESLint v0.0.9 中引入。