Eslint
规则 | Rules

consistent-this

Require Consistent This (consistent-this)

通常需要捕获当前的执行环境以便随后可用。一个突出的例子是 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"选项:/ * eslint consistent-this:["error", "that"]*/ var that = 42; var self = this; that = 42; self = this;Examples of correct code for this rule with the default "that" option:/*eslint consistent-this: ["error", "that"]*/ var that = this; var self = 42; var self; that = this; foo.bar = this;