以下打字稿編譯沒有錯誤:爲什麼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'
不該」即使變量拼寫正確,這個錯誤也會發生嗎?
作品:
您可以通過嘗試分配一個值to any other
window
properties.實例測試自己這一點。 JS版本在節點6.0上運行時沒有錯誤 – C14L