我猜不出为什么会在下面的代码中发生这种情况:
(function(){
console.log(`v1: `,v1); // show "undefined"
console.log(`v2: `,v2); // show "Uncaught ReferenceError: v2 is not defined"
if (true) {
var v1 = 'something';
}
})();
为什么 v1
显示 undefined
?在必须喜欢 v2
的情况下,因为 v1
定义在 if
block 中。
最佳答案
这是因为 Hoisting
. v1
的声明先发生,然后是赋值。
您的代码实际解释为:
(function(){
var v1;
console.log(`v1: `,v1); // show "undefined"
console.log(`v2: `,v2); // show "Uncaught ReferenceError: v2 is not defined"
if (true) {
v1 = 'something';
}
})();
关于嵌套范围内的 JavaScript 变量在范围外不会出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50226203/