【发布时间】:2015-12-08 06:50:46
【问题描述】:
我正在学习 JavaScript 中的变量提升,发现这种行为很奇怪:
var x = 0;
(function () {
//Variable declaration from the if statement is hoisted:
//var x; //undefined
console.log(x); //undefined
if (x === undefined) {
var x = 1; //This statement jumps to the top of the function in form of a variable declaration, and makes the condition become true.
}
}());
是否正确,在这种情况下,语句使条件为真以便可以执行?
【问题讨论】:
-
var是函数作用域,而不是块作用域。 -
您会期望什么行为(以及为什么/如何)?
-
注意:你可以使用
let来声明一个块范围的变量(MDN)
标签: javascript hoisting