Versions

consistent-this

Enforce consistent naming when capturing the current execution context

通常有必要捕获当前的执行环境,以使其随后可用。这方面一个突出的例子是 jQuery 的回调。

var 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" 选项的错误示例:

Open in Playground
/*eslint consistent-this: ["error", "that"]*/

var that = 42;

var self = this;

that = 42;

self = this;

使用此规则与默认的 "that" 选项的正确示例:

Open in Playground
/*eslint consistent-this: ["error", "that"]*/

var that = this;

var self = 42;

var self;

that = this;

foo.bar = this;

如果变量没有被初始化,使用此规则与默认的 "that" 选项的错误示例:

Open in Playground
/*eslint consistent-this: ["error", "that"]*/

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

如果变量没有被初始化,使用此规则与默认的 "that" 选项的正确示例:

Open in Playground
/*eslint consistent-this: ["error", "that"]*/

var that;
that = this;

var foo, that;
foo = 42;
that = this;

何时不用

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

Version

This rule was introduced in ESLint v0.0.9.

Resources

更改语言