使用 var 關(guān)鍵字聲明的變量的作用域?yàn)閯?chuàng)建它們的函數(shù),或者如果在任何函數(shù)外部創(chuàng)建,則為全局對(duì)象。 let 和 const 是塊作用域的,這意味著它們只能在最近的一組花括號(hào)(函數(shù)、if-else 塊或 for 循環(huán))內(nèi)訪問(wèn)。
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
登錄后復(fù)制
var 允許變量被提升,這意味著它們可以在聲明之前在代碼中引用。 let 和 const 不會(huì)允許這樣做,而是會(huì)拋出錯(cuò)誤。
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';
登錄后復(fù)制
用var重新聲明變量不會(huì)報(bào)錯(cuò),但let和const會(huì)報(bào)錯(cuò)
var foo = 'foo'; var foo = 'bar'; console.log(foo); // "bar" let baz = 'baz'; let baz = 'qux'; // uncaught syntaxerror: identifier 'baz' has already been declared
登錄后復(fù)制
let 和 const 的區(qū)別在于 let 允許重新分配變量的值,而 const 則不允許。
// This is fine. let foo = 'foo'; foo = 'bar'; // This causes an exception. const baz = 'baz'; baz = 'qux';
登錄后復(fù)制