Enforce consistent naming when capturing the current execution context
This rule is currently frozen and is not accepting feature requests.
It is often necessary to capture the current execution context in order to make it available subsequently. A prominent example of this are jQuery callbacks:
const that = this;
jQuery('li').click(function (event) {
// here, "this" is the HTMLElement where the click event occurred
that.setFoo(42);
});
There are many commonly used aliases for this such as that, self or me. It is desirable to ensure that whichever alias the team agrees upon is used consistently throughout the application.
This rule enforces two things about variables with the designated alias names for this:
this.this, the name of the variable must be a designated alias.This rule has one or more string options:
this (default "that")Examples of incorrect code for this rule with the default "that" option:
/*eslint consistent-this: ["error", "that"]*/
let ;
let ;
;
;
Examples of correct code for this rule with the default "that" option:
/*eslint consistent-this: ["error", "that"]*/
let that = this;
const self = 42;
let foo;
that = this;
foo.bar = this;
Examples of incorrect code for this rule with the default "that" option, if the variable is not initialized:
/*eslint consistent-this: ["error", "that"]*/
let ;
function f() {
that = this;
}
Examples of correct code for this rule with the default "that" option, if the variable is not initialized:
Declaring a variable that and assigning this to it.
/*eslint consistent-this: ["error", "that"]*/
let that;
that = this;
Declaring two variables, foo and that, with foo initialized, and then assigning this to that.
/*eslint consistent-this: ["error", "that"]*/
let foo = 42, that;
that = this;
If you need to capture nested context, consistent-this is going to be problematic. Code of that nature is usually difficult to read and maintain and you should consider refactoring it.
This rule was introduced in ESLint v0.0.9.
© OpenJS Foundation and other contributors
Licensed under the MIT License.
https://eslint.org/docs/latest/rules/consistent-this