使用 var 關鍵字聲明的變數的作用域為創建它們的函數,或者如果在任何函數外部創建,則為全域物件。 let 和 const 是區塊作用域的,這意味著它們只能在最近的一組花括號(函數、if-else 區塊或 for 迴圈)中存取。
function foo() { // All variables are accessible within functions. var bar = 'bar'; let baz = 'baz'; const qux = 'qux'; console.log(bar); // bar console.log(baz); // baz console.log(qux); // qux } console.log(bar); // ReferenceError: bar is not defined console.log(baz); // ReferenceError: baz is not defined console.log(qux); // ReferenceError: qux is not defined if (true) { var bar = 'bar'; let baz = 'baz'; const qux = 'qux'; } // var declared variables are accessible anywhere in the function scope. console.log(bar); // bar // let and const defined variables are not accessible outside the block they were defined in. console.log(baz); // ReferenceError: baz is not defined console.log(qux); // ReferenceError: qux is not defined
var 允許變數被提升,這意味著它們可以在聲明之前在程式碼中引用。 let 和 const 不允許這樣做,而是拋出錯誤。
console.log(foo); // undefined var foo = 'foo'; console.log(baz); // ReferenceError: can't access lexical declaration 'baz' before initialization let baz = 'baz'; console.log(bar); // ReferenceError: can't access lexical declaration 'bar' before initialization const bar = 'bar';
用 var 重新宣告變數不會拋出錯誤,但 let 和 const 會拋出錯誤。
var foo = 'foo'; var foo = 'bar'; console.log(foo); // "bar" let baz = 'baz'; let baz = 'qux'; // Uncaught SyntaxError: Identifier 'baz' has already been declared
let 和 const 的不同之處在於 let 允許重新分配變數的值,而 const 則不允許。
// This is fine. let foo = 'foo'; foo = 'bar'; // This causes an exception. const baz = 'baz'; baz = 'qux';
以上是let、var 或 const 有什麼不同?的詳細內容。更多資訊請關注PHP中文網其他相關文章!