2 * @fileoverview Rule to enforce that all class methods use 'this'.
3 * @author Patrick Williams
8 //------------------------------------------------------------------------------
10 //------------------------------------------------------------------------------
12 const astUtils = require("./utils/ast-utils");
14 //------------------------------------------------------------------------------
16 //------------------------------------------------------------------------------
23 description: "enforce that class methods utilize `this`",
24 category: "Best Practices",
26 url: "https://eslint.org/docs/rules/class-methods-use-this"
39 additionalProperties: false
43 missingThis: "Expected 'this' to be used by class {{name}}."
47 const config = Object.assign({}, context.options[0]);
48 const exceptMethods = new Set(config.exceptMethods || []);
53 * Initializes the current context to false and pushes it onto the stack.
54 * These booleans represent whether 'this' has been used in the context.
58 function enterFunction() {
63 * Check if the node is an instance method
64 * @param {ASTNode} node node to check
65 * @returns {boolean} True if its an instance method
68 function isInstanceMethod(node) {
69 return !node.static && node.kind !== "constructor" && node.type === "MethodDefinition";
73 * Check if the node is an instance method not excluded by config
74 * @param {ASTNode} node node to check
75 * @returns {boolean} True if it is an instance method, and not excluded by config
78 function isIncludedInstanceMethod(node) {
79 return isInstanceMethod(node) &&
80 (node.computed || !exceptMethods.has(node.key.name));
84 * Checks if we are leaving a function that is a method, and reports if 'this' has not been used.
85 * Static methods and the constructor are exempt.
86 * Then pops the context off the stack.
87 * @param {ASTNode} node A function node that was entered.
91 function exitFunction(node) {
92 const methodUsesThis = stack.pop();
94 if (isIncludedInstanceMethod(node.parent) && !methodUsesThis) {
97 messageId: "missingThis",
99 name: astUtils.getFunctionNameWithKind(node)
106 * Mark the current context as having used 'this'.
110 function markThisUsed() {
112 stack[stack.length - 1] = true;
117 FunctionDeclaration: enterFunction,
118 "FunctionDeclaration:exit": exitFunction,
119 FunctionExpression: enterFunction,
120 "FunctionExpression:exit": exitFunction,
121 ThisExpression: markThisUsed,