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
有很多常用的别名,例如 that
、self
或 me
。最好确保团队同意的任何别名在整个应用程序中始终如一地使用。
规则详情
此规则对具有指定别名 this
的变量强制执行两件事:
- 如果声明了具有指定名称的变量,则必须将其初始化(在声明中)或分配(在与声明相同的范围内)值
this
。 - 如果变量被初始化或赋值为
this
,则变量的名称必须是指定的别名。
选项
9NHbribgvlAIiqeVNtZmFLsnjN2t5hwvv1eRnt1MTsX2XLMFtNAh+8BOX7h818pt
- GrTmCvEMeL2prd/t+It5GiRtD5A+kM80K3yyYHCtEr7ywfX40Dp7wrtTrnwd/Ztop5BEnUweN1fxLITO2nDrX+66cmKkokHr2uXiPPjwoDVKIxJ/0wZeUEBxvUovwHof
1usau4ITNzPbSW1XK9odV+vkES//Hhni2vawRJuUE7o8dpLu6+XN/DRj+W+0NPYkXHf1aaz1sy1weQK4GukSyEe0DzyxH/EnQmvN/tcBwx0=
/*eslint consistent-this: ["error", "that"]*/
var that = 42;
var self = this;
that = 42;
self = this;
1usau4ITNzPbSW1XK9odV+vkES//Hhni2vawRJuUE7o8dpLu6+XN/DRj+W+0NPYkVL2CGt9WREaZtAiSvJxu+VbzkSgGWZlBp5yHjQWq8m4=
/*eslint consistent-this: ["error", "that"]*/
var that = this;
var self = 42;
var self;
that = this;
foo.bar = this;
eQMNpAEyM8GE3lCx0AUF9CFyp6R67F/lDO1cUEv7kDDsNTNn9XxxXQRyyckzTKd28lTAmlgEdKUrMAQOj3POYzqwnfNIal9kC/QRqodGi/IxNFhOzdEh+IFjVVXS0Ik6fAQehxBrHirOVLmqnVZlaQ==
/*eslint consistent-this: ["error", "that"]*/
var that;
function f() {
that = this;
}
eQMNpAEyM8GE3lCx0AUF9HO8qtqT9v58kWKaNOCQJRerDhpPWUdoSuez2OdnK1YymL0/TzJd38emDQ9UlKC67vQUH4dPyn6g4tu1QIE2q6A477ZDsbtLJZPZhGlyGb4yF8oudnIM036D0CVudmcfpA==
/*eslint consistent-this: ["error", "that"]*/
var that;
that = this;
var foo, that;
foo = 42;
that = this;
何时不使用
zjpcWXkNFSGU5oq7OrSv9Iq7HNHgsAVdvvjvP+bUGNZCvYod78jY2P4F6D40SJMCbKj9G/OTa/8PSQAoAhnd69znVEwH/bbiKnDtXTH3DecBfTepqQENwsdvk45pTcoq0CwQInQef84QviuLVp+z17Tu8flbXm0QiCjHpYm9sODCsIiECo0m1UPiD98Hsri47XEqgm99uSHpFx2bZAT16DjiedSTbCOPzu5h9+FFfVM=