我正在学习JavaScript,并在mdn上遇到了有关const行为的示例:
const MY_FAV = 7;
// it's important to note the nature of block scoping
if (MY_FAV === 7) {
// this is fine and creates a block scoped MY_FAV variable
// (works equally well with let to declare a block scoped non const variable)
let MY_FAV = 20;
// MY_FAV is now 20
console.log('my favorite number is ' + MY_FAV);
// this gets hoisted into the global context and throws an error
var MY_FAV = 20;
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const
我知道您不能在let和const之后用var重新声明变量。 但是评论说这是悬挂的。为什么 var MY_FAV = 20; 被吊起?实际发生了什么?
谢谢
编辑:这不是重复的,因为没有讨论块中的var行为以及块中let和const之间的区别。
答案 0 :(得分:1)
您的代码示例与
基本上相同var MY_FAV = 20;
const MY_FAV = 7;
// it's important to note the nature of block scoping
if (MY_FAV === 7) {
// this is fine and creates a block scoped MY_FAV variable
// (works equally well with let to declare a block scoped non const variable)
let MY_FAV = 20;
// MY_FAV is now 20
console.log('my favorite number is ' + MY_FAV);
}
基本上,var MY_FAV = 20;
是第一个MY_FAV
声明,它导致const MY_FAV = 7;
抛出错误,因为它已经被声明了。
答案 1 :(得分:0)
使用let
或const
声明的变量和常量不会被吊起,而使用var
声明的变量和常量则被吊起。
正在发生的事情是var MY_FAV = 20;
被吊起,然后尝试重新声明。