no-new-object.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /**
  2. * @fileoverview A rule to disallow calls to the Object constructor
  3. * @author Matt DuVall <http://www.mattduvall.com/>
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Requirements
  8. //------------------------------------------------------------------------------
  9. const astUtils = require("./utils/ast-utils");
  10. //------------------------------------------------------------------------------
  11. // Rule Definition
  12. //------------------------------------------------------------------------------
  13. /** @type {import('../shared/types').Rule} */
  14. module.exports = {
  15. meta: {
  16. type: "suggestion",
  17. docs: {
  18. description: "Disallow `Object` constructors",
  19. recommended: false,
  20. url: "https://eslint.org/docs/rules/no-new-object"
  21. },
  22. schema: [],
  23. messages: {
  24. preferLiteral: "The object literal notation {} is preferable."
  25. }
  26. },
  27. create(context) {
  28. const sourceCode = context.getSourceCode();
  29. return {
  30. NewExpression(node) {
  31. const variable = astUtils.getVariableByName(
  32. sourceCode.getScope(node),
  33. node.callee.name
  34. );
  35. if (variable && variable.identifiers.length > 0) {
  36. return;
  37. }
  38. if (node.callee.name === "Object") {
  39. context.report({
  40. node,
  41. messageId: "preferLiteral"
  42. });
  43. }
  44. }
  45. };
  46. }
  47. };