2016-05-24 24 views
2

以下打字稿編譯沒有錯誤:爲什麼TypeScript在方法中允許「this」被省略?

class Something { 

    name: string; 

    constructor() { 
     name = "test"; 
    } 

} 

此代碼編譯沒有錯誤,似乎認爲這個名字變量存在。但是它產生的js將無法運行,因爲我已經省略了this關鍵字:

/Users/cburtbrown/Documents/code/ts/js/tstest.js:6 
     console.log(name); 
        ^

ReferenceError: name is not defined 
    at Something.action (/Users/cburtbrown/Documents/code/ts/js/tstest.js:6:21) 
    at Object.<anonymous> (/Users/cburtbrown/Documents/code/ts/js/tstest.js:10:25) 
    at Module._compile (module.js:541:32) 
    at Object.Module._extensions..js (module.js:550:10) 
    at Module.load (module.js:456:32) 
    at tryModuleLoad (module.js:415:12) 
    at Function.Module._load (module.js:407:3) 
    at Function.Module.runMain (module.js:575:10) 
    at startup (node.js:159:18) 
    at node.js:444:3 

如果我輸錯在構造函數中的變量那麼它失敗,此錯誤:

Cannot find name 'namej' 

不該」即使變量拼寫正確,這個錯誤也會發生嗎?

+0

作品:

您可以通過嘗試分配一個值to any other window properties.

實例測試自己這一點。 JS版本在節點6.0上運行時沒有錯誤 – C14L

回答

5

因爲the window object has a name property.

至於打字稿而言,你試圖分配一個值,這個屬性。當然,如果你沒有在瀏覽器中運行,這會失敗。我

class Something { 
    name: string; 

    constructor() { 
     status = "test"; 
    } 
} 
+1

哦,我明白了,所以它特別是'name'。沒有考慮到這種可能性。感謝你及時的答覆! –

+0

在節點6.0上編譯得很好,這裏沒有'window'。 – C14L

+2

@ C14L他說它編譯得很好,但無法正常運行。如果你沒有使用嚴格模式,那麼它會運行,因爲你創建一個隱式的全局。 –

相關問題