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
,則變數的名稱必須是指定的別名。
選項
此規則具有一個或多個字串選項
this
的指定別名名稱(預設為"that"
)
使用預設 "that"
選項時,此規則的不正確程式碼範例
在遊樂場中開啟
/*eslint consistent-this: ["error", "that"]*/
var ;
var ;
;
;
使用預設 "that"
選項時,此規則的正確程式碼範例
在遊樂場中開啟
/*eslint consistent-this: ["error", "that"]*/
var that = this;
var self = 42;
var self;
that = this;
foo.bar = this;
如果變數未初始化,使用預設 "that"
選項時,此規則的不正確程式碼範例
在遊樂場中開啟
/*eslint consistent-this: ["error", "that"]*/
var that;
function f() {
that = this;
}
如果變數未初始化,使用預設 "that"
選項時,此規則的正確程式碼範例
在遊樂場中開啟
/*eslint consistent-this: ["error", "that"]*/
var that;
that = this;
var foo, that;
foo = 42;
that = this;
何時不使用它
如果您需要捕獲巢狀上下文,consistent-this
將會產生問題。這種性質的程式碼通常難以閱讀和維護,您應該考慮重構它。
版本
此規則在 ESLint v0.0.9 中引入。