no-this-assignment.js 1018 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. 'use strict';
  2. const {matches} = require('./selectors/index.js');
  3. const MESSAGE_ID = 'no-this-assignment';
  4. const messages = {
  5. [MESSAGE_ID]: 'Do not assign `this` to `{{name}}`.',
  6. };
  7. const variableDeclaratorSelector = [
  8. 'VariableDeclarator',
  9. '[init.type="ThisExpression"]',
  10. '[id.type="Identifier"]',
  11. ].join('');
  12. const assignmentExpressionSelector = [
  13. 'AssignmentExpression',
  14. '[right.type="ThisExpression"]',
  15. '[left.type="Identifier"]',
  16. ].join('');
  17. const selector = matches([variableDeclaratorSelector, assignmentExpressionSelector]);
  18. /** @param {import('eslint').Rule.RuleContext} context */
  19. const create = () => ({
  20. [selector](node) {
  21. const variable = node.type === 'AssignmentExpression' ? node.left : node.id;
  22. return {
  23. node,
  24. data: {name: variable.name},
  25. messageId: MESSAGE_ID,
  26. };
  27. },
  28. });
  29. /** @type {import('eslint').Rule.RuleModule} */
  30. module.exports = {
  31. create,
  32. meta: {
  33. type: 'suggestion',
  34. docs: {
  35. description: 'Disallow assigning `this` to a variable.',
  36. },
  37. messages,
  38. },
  39. };