no-case-declarations
禁止在 case 子句中使用詞法宣告
此規則禁止在 case
/default
子句中使用詞法宣告(let
、const
、function
和 class
)。原因是詞法宣告在整個 switch 區塊中可見,但只有在分配時才會初始化,而這只會在到達定義它的 case 時才會發生。
為了確保詞法宣告只適用於目前的 case 子句,請將您的子句包在區塊中。
規則詳情
此規則旨在防止存取未初始化的詞法綁定,以及跨 case 子句存取提升的函式。
此規則的不正確程式碼範例
在遊樂場中開啟
/*eslint no-case-declarations: "error"*/
switch (foo) {
case 1:
break;
case 2:
break;
case 3:
break;
default:
}
此規則的正確程式碼範例
在遊樂場中開啟
/*eslint no-case-declarations: "error"*/
// Declarations outside switch-statements are valid
const a = 0;
switch (foo) {
// The following case clauses are wrapped into blocks using brackets
case 1: {
let x = 1;
break;
}
case 2: {
const y = 2;
break;
}
case 3: {
function f() {}
break;
}
case 4:
// Declarations using var without brackets are valid due to function-scope hoisting
var z = 4;
break;
default: {
class C {}
}
}
何時不應使用它
如果您依賴向下傳遞的行為,並想要存取 case 區塊中引入的綁定。
相關規則
版本
此規則是在 ESLint v1.9.0 中引入的。