版本

consistent-this

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

❄️ 已冻结

此规则目前处于冻结状态,不接受功能请求。

通常有必要捕获当前的执行上下文,以便后续使用。一个突出的例子是 jQuery 回调

const that = this;
jQuery('li').click(function (event) {
    // here, "this" is the HTMLElement where the click event occurred
    that.setFoo(42);
});

对于 this,有很多常用的别名,例如 thatselfme。 确保团队达成一致的任何别名在整个应用程序中一致使用是可取的。

规则详情

此规则强制执行关于具有 this 的指定别名名称的变量的两件事

  • 如果声明了具有指定名称的变量,则它必须被初始化(在声明中)或赋值(在与声明相同的范围内)为值 this
  • 如果变量被初始化或赋值为值 this,则变量的名称必须是指定的别名。

选项

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

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

此规则的不正确代码示例,使用默认的 "that" 选项

在 Playground 中打开
/*eslint consistent-this: ["error", "that"]*/

let that = 42;

let self = this;

that = 42;

self = this;

此规则的正确代码示例,使用默认的 "that" 选项

在 Playground 中打开
/*eslint consistent-this: ["error", "that"]*/

let that = this;

const self = 42;

let foo;

that = this;

foo.bar = this;

此规则的不正确代码示例,使用默认的 "that" 选项,如果变量未初始化

在 Playground 中打开
/*eslint consistent-this: ["error", "that"]*/

let that;
function f() {
    that = this;
}

此规则的正确代码示例,使用默认的 "that" 选项,如果变量未初始化

声明一个变量 that 并将 this 赋值给它。

在 Playground 中打开
/*eslint consistent-this: ["error", "that"]*/

let that;
that = this;

声明两个变量,foothat,其中 foo 已初始化,然后将 this 赋值给 that

在 Playground 中打开
/*eslint consistent-this: ["error", "that"]*/

let foo = 42, that;
that = this;

何时不使用

如果您需要捕获嵌套上下文,consistent-this 将会变得有问题。 这种性质的代码通常难以阅读和维护,您应该考虑重构它。

版本

此规则在 ESLint v0.0.9 中引入。

资源

更改语言