consistent-this
在捕获当前执行上下文时强制执行一致的命名
此规则目前已 冻结,不接受功能请求。
通常有必要捕获当前的执行上下文,以便随后可以使用它。一个显著的例子就是 jQuery 回调:
🌐 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);
});
this 有许多常用别名,例如 that、self 或 me。最好确保无论团队达成一致使用哪个别名,都在整个应用中保持一致使用。
🌐 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.
规则详情
🌐 Rule Details
此规则对具有指定别名 this 的变量强制执行两件事:
🌐 This rule enforces two things about variables with the designated alias names for this:
- 如果声明了一个具有指定名称的变量,它必须要么在声明时初始化,要么在与声明相同的作用域中赋值为值
this。 - 如果一个变量被初始化或赋值为
this,该变量的名称必须是一个指定的别名。
选项
🌐 Options
此规则有一个或多个字符串选项:
🌐 This rule has one or more string options:
this的指定别名(默认"that")
使用默认 "that" 选项时,该规则的错误代码示例:
🌐 Examples of incorrect code for this rule with the default "that" option:
/*eslint consistent-this: ["error", "that"]*/
let that = 42;
let self = this;
that = 42;
self = this;
使用默认 "that" 选项时,该规则的正确代码示例:
🌐 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;
使用默认 "that" 选项时,如果变量未初始化,该规则的错误代码示例:
🌐 Examples of incorrect code for this rule with the default "that" option, if the variable is not initialized:
/*eslint consistent-this: ["error", "that"]*/
let that;
function f() {
that = this;
}
如果变量未初始化,使用默认 "that" 选项时,该规则的正确代码示例:
🌐 Examples of correct code for this rule with the default "that" option, if the variable is not initialized:
声明一个变量 that 并将 this 赋值给它。
🌐 Declaring a variable that and assigning this to it.
/*eslint consistent-this: ["error", "that"]*/
let that;
that = this;
声明两个变量 foo 和 that,并初始化 foo,然后将 this 赋值给 that。
🌐 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;
何时不使用
🌐 When Not To Use It
如果你需要捕获嵌套上下文,consistent-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.
版本
此规则是在 ESLint v0.0.9 中引入。