no-new-object.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /**
  2. * @fileoverview A rule to disallow calls to the Object constructor
  3. * @author Matt DuVall <http://www.mattduvall.com/>
  4. * @deprecated in ESLint v8.50.0
  5. */
  6. "use strict";
  7. //------------------------------------------------------------------------------
  8. // Requirements
  9. //------------------------------------------------------------------------------
  10. const astUtils = require("./utils/ast-utils");
  11. //------------------------------------------------------------------------------
  12. // Rule Definition
  13. //------------------------------------------------------------------------------
  14. /** @type {import('../types').Rule.RuleModule} */
  15. module.exports = {
  16. meta: {
  17. type: "suggestion",
  18. docs: {
  19. description: "Disallow `Object` constructors",
  20. recommended: false,
  21. url: "https://eslint.org/docs/latest/rules/no-new-object",
  22. },
  23. deprecated: {
  24. message:
  25. "The new rule flags more situations where object literal syntax can be used, and it does not report a problem when the `Object` constructor is invoked with an argument.",
  26. url: "https://eslint.org/blog/2023/09/eslint-v8.50.0-released/",
  27. deprecatedSince: "8.50.0",
  28. availableUntil: "11.0.0",
  29. replacedBy: [
  30. {
  31. rule: {
  32. name: "no-object-constructor",
  33. url: "https://eslint.org/docs/rules/no-object-constructor",
  34. },
  35. },
  36. ],
  37. },
  38. schema: [],
  39. messages: {
  40. preferLiteral: "The object literal notation {} is preferable.",
  41. },
  42. },
  43. create(context) {
  44. const sourceCode = context.sourceCode;
  45. return {
  46. NewExpression(node) {
  47. const variable = astUtils.getVariableByName(
  48. sourceCode.getScope(node),
  49. node.callee.name,
  50. );
  51. if (variable && variable.identifiers.length > 0) {
  52. return;
  53. }
  54. if (node.callee.name === "Object") {
  55. context.report({
  56. node,
  57. messageId: "preferLiteral",
  58. });
  59. }
  60. },
  61. };
  62. },
  63. };