使用 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';
登錄后復制