我正在嘗試了解新的函式語法。當我使用 let 宣告變數 'value' 時,它會給出 'ReferenceError: value is not defined' 錯誤,但如果我使用 var 或不使用 var,輸出將列印為測驗。我假設 'value' 變數是全域的,因為它是在外部定義的。但是為什么它可以使用 var 而不是 let 雖然兩者都是全域變數。?
let value = "test";
function getFunc() {
// value = "test";
let func = new Function('console.log(value)');
return func;
}
getFunc()();
uj5u.com熱心網友回復:
在頂層let, 與 不同var,不會在全域物件上創建屬性。
var foo = "Foo"; // globally scoped
let bar = "Bar"; // not allowed to be globally scoped
console.log(window.foo); // Foo
console.log(window.bar); // undefined
參考
因此let只能在由 表示的封閉塊內使用{}。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/342959.html
