鍍金池/ 問答/HTML/ esLint里no-case-declarations的意義在哪

esLint里no-case-declarations的意義在哪

官網的解釋:The reason is that the lexical declaration is visible in the entire switch block but it only gets initialized when it is assigned, which will only happen if the case where it is defined is reached.
沒怎么看懂

回答
編輯回答
撿肥皂

有中文網站 no-case-declarations

該規(guī)則禁止詞法聲明 (let、const、functionclass) 出現在 casedefault 子句中。原因是,詞法聲明在整個 switch 語句塊中是可見的,但是它只有在運行到它定義的 case 語句時,才會進行初始化操作。

為了保證詞法聲明語句只在當前 case 語句中有效,將你子句包裹在塊中。

該規(guī)則旨在避免訪問未經初始化的詞法綁定以及跨 case 語句訪問被提升的函數。

switch (foo) {
    case 1:
        let x = 1;
        break;
    case 2:
        const y = 2;
        break;
    case 3:
        function f() {}
        break;
    default:
        class C {}
}

大概是指上面case 1里的xcase 2里也會生效,所以要用{}包起來,防止x提升到整個switch語句。

2017年10月24日 01:18