Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Fix: no check for shadowed Object (fixes #12809) (#13115)
  • Loading branch information
anikethsaha committed Apr 1, 2020
1 parent 988d842 commit 7551f0c
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 9 deletions.
5 changes: 4 additions & 1 deletion docs/rules/no-new-object.md
Expand Up @@ -27,7 +27,7 @@ Examples of **incorrect** code for this rule:

var myObject = new Object();

var myObject = new Object;
new Object();
```

Examples of **correct** code for this rule:
Expand All @@ -38,6 +38,9 @@ Examples of **correct** code for this rule:
var myObject = new CustomObject();

var myObject = {};

var Object = function Object() {};
new Object();
```

## When Not To Use It
Expand Down
18 changes: 15 additions & 3 deletions lib/rules/no-new-object.js
Expand Up @@ -5,6 +5,12 @@

"use strict";

//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------

const astUtils = require("./utils/ast-utils");

//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
Expand All @@ -28,10 +34,17 @@ module.exports = {
},

create(context) {

return {

NewExpression(node) {
const variable = astUtils.getVariableByName(
context.getScope(),
node.callee.name
);

if (variable && variable.identifiers.length > 0) {
return;
}

if (node.callee.name === "Object") {
context.report({
node,
Expand All @@ -40,6 +53,5 @@ module.exports = {
}
}
};

}
};
45 changes: 40 additions & 5 deletions tests/lib/rules/no-new-object.js
Expand Up @@ -20,15 +20,50 @@ const ruleTester = new RuleTester();

ruleTester.run("no-new-object", rule, {
valid: [
"var foo = new foo.Object()"
"var myObject = {};",
"var myObject = new CustomObject();",
"var foo = new foo.Object()",
`var Object = function Object() {};
new Object();`,
`var x = something ? MyClass : Object;
var y = new x();`,
{
code: `
class Object {
constructor(){
}
}
new Object();
`,
parserOptions: { ecmaVersion: 6 }
},
{
code: `
import { Object } from './'
new Object();
`,
parserOptions: { ecmaVersion: 6, sourceType: "module" }
}
],
invalid: [
{
code: "var foo = new Object()",
errors: [{
messageId: "preferLiteral",
type: "NewExpression"
}]
errors: [
{
messageId: "preferLiteral",
type: "NewExpression"
}
]
},
{
code: "new Object();",
errors: [{ messageId: "preferLiteral", type: "NewExpression" }]
},
{
code: "const a = new Object()",
parserOptions: { ecmaVersion: 6 },
errors: [{ messageId: "preferLiteral", type: "NewExpression" }]
}
]
});

0 comments on commit 7551f0c

Please sign in to comment.