blob: e9f915db5eaa9173dfe8a094da8dbdcd7b519252 [file] [log] [blame]
Yang Guo4fd355c2019-09-19 10:59:03 +02001/**
2 * @fileoverview A rule to disallow calls to the Object constructor
3 * @author Matt DuVall <http://www.mattduvall.com/>
4 */
5
6"use strict";
7
8//------------------------------------------------------------------------------
Tim van der Lippe16aca392020-11-13 11:37:13 +00009// Requirements
10//------------------------------------------------------------------------------
11
12const astUtils = require("./utils/ast-utils");
13
14//------------------------------------------------------------------------------
Yang Guo4fd355c2019-09-19 10:59:03 +020015// Rule Definition
16//------------------------------------------------------------------------------
17
18module.exports = {
19 meta: {
20 type: "suggestion",
21
22 docs: {
23 description: "disallow `Object` constructors",
24 category: "Stylistic Issues",
25 recommended: false,
26 url: "https://eslint.org/docs/rules/no-new-object"
27 },
28
Tim van der Lippe16aca392020-11-13 11:37:13 +000029 schema: [],
30
31 messages: {
32 preferLiteral: "The object literal notation {} is preferrable."
33 }
Yang Guo4fd355c2019-09-19 10:59:03 +020034 },
35
36 create(context) {
Yang Guo4fd355c2019-09-19 10:59:03 +020037 return {
Yang Guo4fd355c2019-09-19 10:59:03 +020038 NewExpression(node) {
Tim van der Lippe16aca392020-11-13 11:37:13 +000039 const variable = astUtils.getVariableByName(
40 context.getScope(),
41 node.callee.name
42 );
43
44 if (variable && variable.identifiers.length > 0) {
45 return;
46 }
47
Yang Guo4fd355c2019-09-19 10:59:03 +020048 if (node.callee.name === "Object") {
Tim van der Lippe16aca392020-11-13 11:37:13 +000049 context.report({
50 node,
51 messageId: "preferLiteral"
52 });
Yang Guo4fd355c2019-09-19 10:59:03 +020053 }
54 }
55 };
Yang Guo4fd355c2019-09-19 10:59:03 +020056 }
57};