no-new-object.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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. return {
  29. NewExpression(node) {
  30. const variable = astUtils.getVariableByName(
  31. context.getScope(),
  32. node.callee.name
  33. );
  34. if (variable && variable.identifiers.length > 0) {
  35. return;
  36. }
  37. if (node.callee.name === "Object") {
  38. context.report({
  39. node,
  40. messageId: "preferLiteral"
  41. });
  42. }
  43. }
  44. };
  45. }
  46. };