如果声明和变量提升

时间:2015-12-08 06:50:46

标签: javascript hoisting

我正在学习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.
    }
}());

是否正确,在这种情况下,语句使条件成立,以便可以执行?

2 个答案:

答案 0 :(得分:4)

仅提升提升声明,但不提升任务。您的代码相当于:

var x = 0;

(function () {
    //Variable declaration from the if statement is hoisted:
    var x;

    console.log(x); //undefined

    if (x === undefined) {
        x = 1;
    }
}());

if语句的条件表达式的计算结果为true,并且已达到x = 1

答案 1 :(得分:1)

顺便说一句,如果你在if语句中声明一个变量,无论if条件是否传递,声明总是被托管。例如:



console.log(a); //undefined , not respond ReferenceError ,it has been hoisted
if(true){
  var a=1;
}
console.log(b); //same as above
if(false){
  var b=1;
}