diff --git a/docs/rules/no-new-object.md b/docs/rules/no-new-object.md index 5186682fc058..20a01030ffac 100644 --- a/docs/rules/no-new-object.md +++ b/docs/rules/no-new-object.md @@ -40,6 +40,30 @@ var myObject = new CustomObject(); var myObject = {}; ``` +## Options + +This rule has a single `allowWithArguments` option. + +### allowWithArguments + +One can coerce primitives into objects by passing `new Object()` an argument. +This option allows for this use case. (Coercing to an object might be desired +if enhancing or polyfilling an object's prototype.) + +Examples of **incorrect** code for the `{ "allowWithArguments": true }` option: + +```js +/*eslint no-new-object: [2, { "allowWithArguments": true }]*/ +var myObject = new Object(); +``` + +Examples of **correct** code for the `{ "allowWithArguments": true }` option: + +```js +/*eslint no-new-object: [2, { "allowWithArguments": true }]*/ +var myObject = new Object(BigInt('1n')); +``` + ## When Not To Use It If you wish to allow the use of the `Object` constructor, you can safely turn this rule off. diff --git a/lib/rules/no-new-object.js b/lib/rules/no-new-object.js index f5cc28664f4e..139a53a761aa 100644 --- a/lib/rules/no-new-object.js +++ b/lib/rules/no-new-object.js @@ -24,11 +24,14 @@ module.exports = { }, create(context) { + const { allowWithArguments } = context.options[0] || {}; return { NewExpression(node) { - if (node.callee.name === "Object") { + if (node.callee.name === "Object" && ( + !allowWithArguments || !node.arguments.length + )) { context.report({ node, message: "The object literal notation {} is preferrable." }); } } diff --git a/tests/lib/rules/no-new-object.js b/tests/lib/rules/no-new-object.js index b0fb22e370ba..6b0cee12cd76 100644 --- a/tests/lib/rules/no-new-object.js +++ b/tests/lib/rules/no-new-object.js @@ -20,9 +20,16 @@ const ruleTester = new RuleTester(); ruleTester.run("no-new-object", rule, { valid: [ - "var foo = new foo.Object()" + "var foo = new foo.Object()", + { + code: "var foo = new Object(BigInt('1n'))", + options: [ + { allowWithArguments: true } + ] + } ], invalid: [ - { code: "var foo = new Object()", errors: [{ message: "The object literal notation {} is preferrable.", type: "NewExpression" }] } + { code: "var foo = new Object()", errors: [{ message: "The object literal notation {} is preferrable.", type: "NewExpression" }] }, + { code: "var foo = new Object(BigInt('1n'))", errors: [{ message: "The object literal notation {} is preferrable.", type: "NewExpression" }] } ] });