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. module.exports = {
  14. meta: {
  15. type: "suggestion",
  16. docs: {
  17. description: "disallow `Object` constructors",
  18. category: "Stylistic Issues",
  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 preferrable."
  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. };