【问题标题】:If statement and variable hoistingif 语句和变量提升
【发布时间】: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


【解决方案1】:

提升只提升声明,但不提升分配。您的代码相当于:

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

【讨论】:

    【解决方案2】:

    顺便说一句,如果你在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;
    }

    【讨论】:

      猜你喜欢
      • 2013-10-12
      • 1970-01-01
      • 1970-01-01
      • 2014-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多