使用 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';
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3