consistent-this

在捕获当前执行上下文时强制执行一致的命名

❄️ Frozen

This rule is currently frozen and is not accepting feature requests.

通常需要捕获当前的执行上下文,以便随后可用。一个突出的例子是 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 有很多常用的别名,例如 thatselfme。最好确保团队同意的任何别名在整个应用中始终如一地使用。

¥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

    ¥If a variable with a designated name is declared, it must be either initialized (in the declaration) or assigned (in the same scope as the declaration) the value this.

  • 如果变量被初始化或赋值为 this,则变量的名称必须是指定的别名。

    ¥If a variable is initialized or assigned the value this, the name of the variable must be a designated alias.

选项

¥Options

此规则有一个或多个字符串选项:

¥This rule has one or more string options:

  • this 指定的别名(默认为 "that"

    ¥designated alias names for this (default "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;

声明两个变量 foothat,初始化 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 中引入。

资源