consistent-this
當捕捉當前執行上下文時,強制執行一致的命名
❄️ Frozen
此規則目前為凍結狀態,不接受功能請求。
通常需要捕捉當前執行上下文,以便後續使用。一個顯著的例子是 jQuery 回調
const 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"
選項時,此規則的 錯誤 程式碼範例
在 Playground 中開啟
/*eslint consistent-this: ["error", "that"]*/
let ;
let ;
;
;
使用預設 "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 ;
function f() {
that = this;
}
使用預設 "that"
選項時,如果變數未初始化,此規則的 正確 程式碼範例
宣告變數 that
並將 this
賦值給它。
在 Playground 中開啟
/*eslint consistent-this: ["error", "that"]*/
let that;
that = this;
宣告兩個變數 foo
和 that
,其中 foo
已初始化,然後將 this
賦值給 that
。
在 Playground 中開啟
/*eslint consistent-this: ["error", "that"]*/
let foo = 42, that;
that = this;
何時不該使用
如果您需要捕捉巢狀上下文,consistent-this
將會產生問題。 這種性質的程式碼通常難以閱讀和維護,您應該考慮重構它。
版本
此規則在 ESLint v0.0.9 中引入。