no-invalid-this.js 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. /**
  2. * @fileoverview A rule to disallow `this` keywords in contexts where the value of `this` is `undefined`.
  3. * @author Toru Nagashima
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Requirements
  8. //------------------------------------------------------------------------------
  9. const astUtils = require("./utils/ast-utils");
  10. //------------------------------------------------------------------------------
  11. // Helpers
  12. //------------------------------------------------------------------------------
  13. /**
  14. * Determines if the given code path is a code path with lexical `this` binding.
  15. * That is, if `this` within the code path refers to `this` of surrounding code path.
  16. * @param {CodePath} codePath Code path.
  17. * @param {ASTNode} node Node that started the code path.
  18. * @returns {boolean} `true` if it is a code path with lexical `this` binding.
  19. */
  20. function isCodePathWithLexicalThis(codePath, node) {
  21. return codePath.origin === "function" && node.type === "ArrowFunctionExpression";
  22. }
  23. //------------------------------------------------------------------------------
  24. // Rule Definition
  25. //------------------------------------------------------------------------------
  26. /** @type {import('../shared/types').Rule} */
  27. module.exports = {
  28. meta: {
  29. type: "suggestion",
  30. docs: {
  31. description: "Disallow use of `this` in contexts where the value of `this` is `undefined`",
  32. recommended: false,
  33. url: "https://eslint.org/docs/rules/no-invalid-this"
  34. },
  35. schema: [
  36. {
  37. type: "object",
  38. properties: {
  39. capIsConstructor: {
  40. type: "boolean",
  41. default: true
  42. }
  43. },
  44. additionalProperties: false
  45. }
  46. ],
  47. messages: {
  48. unexpectedThis: "Unexpected 'this'."
  49. }
  50. },
  51. create(context) {
  52. const options = context.options[0] || {};
  53. const capIsConstructor = options.capIsConstructor !== false;
  54. const stack = [],
  55. sourceCode = context.getSourceCode();
  56. /**
  57. * Gets the current checking context.
  58. *
  59. * The return value has a flag that whether or not `this` keyword is valid.
  60. * The flag is initialized when got at the first time.
  61. * @returns {{valid: boolean}}
  62. * an object which has a flag that whether or not `this` keyword is valid.
  63. */
  64. stack.getCurrent = function() {
  65. const current = this[this.length - 1];
  66. if (!current.init) {
  67. current.init = true;
  68. current.valid = !astUtils.isDefaultThisBinding(
  69. current.node,
  70. sourceCode,
  71. { capIsConstructor }
  72. );
  73. }
  74. return current;
  75. };
  76. return {
  77. onCodePathStart(codePath, node) {
  78. if (isCodePathWithLexicalThis(codePath, node)) {
  79. return;
  80. }
  81. if (codePath.origin === "program") {
  82. const scope = context.getScope();
  83. const features = context.parserOptions.ecmaFeatures || {};
  84. // `this` at the top level of scripts always refers to the global object
  85. stack.push({
  86. init: true,
  87. node,
  88. valid: !(
  89. node.sourceType === "module" ||
  90. (features.globalReturn && scope.childScopes[0].isStrict)
  91. )
  92. });
  93. return;
  94. }
  95. /*
  96. * `init: false` means that `valid` isn't determined yet.
  97. * Most functions don't use `this`, and the calculation for `valid`
  98. * is relatively costly, so we'll calculate it lazily when the first
  99. * `this` within the function is traversed. A special case are non-strict
  100. * functions, because `this` refers to the global object and therefore is
  101. * always valid, so we can set `init: true` right away.
  102. */
  103. stack.push({
  104. init: !context.getScope().isStrict,
  105. node,
  106. valid: true
  107. });
  108. },
  109. onCodePathEnd(codePath, node) {
  110. if (isCodePathWithLexicalThis(codePath, node)) {
  111. return;
  112. }
  113. stack.pop();
  114. },
  115. // Reports if `this` of the current context is invalid.
  116. ThisExpression(node) {
  117. const current = stack.getCurrent();
  118. if (current && !current.valid) {
  119. context.report({
  120. node,
  121. messageId: "unexpectedThis"
  122. });
  123. }
  124. }
  125. };
  126. }
  127. };