【问题标题】:JavaScript variable before and after declaration? [duplicate]声明前后的JavaScript变量? [复制]
【发布时间】:2019-10-14 08:16:48
【问题描述】:
function a(){ 
   console.log(typeof b); // function
   function b() {
     var c = 52; 
     console.log(c);
   } 
   var b = 88;  
   console.log(typeof b); // number 
}

谁能回答,javaScript 如何编译或处理这种特殊情况?我知道当涉及到hoisting 时,javaScript 优先考虑function 声明。但是同一个 identifier b 如何在同一个块或同一个词法范围内保存两个不同的值?

有人可能会说,好吧,我将在声明之前将b 用作function,在为其分配number 之后将其用作number

【问题讨论】:

标签: javascript function hoisting


【解决方案1】:

你可以这样理解代码执行有两个阶段

  1. Creation phase
  2. Execution phase

创建阶段:- 在创建阶段,函数按原样提升在顶部,而变量被提升但没有分配值(或者您可以说它的价值是未定义的)

执行阶段:-在执行上下文中,当变量到达发生赋值的行时,它会为变量赋值

所以在你的代码中creation phase 函数 b 被提升,编译器会这样读取它

function a(){ 
   function b(){
     var c = 52; 
     console.log(c);
   } 
   console.log(typeof b); // function
   b = 88;  
   console.log(typeof b); // number 
}

所以当你到达这条线时

b = 88

它为变量b分配一个新值,它的类型为number

【讨论】:

    【解决方案2】:

    在这种情况下,提升发生如下:

    1. 声明var b,不进行初始化
    2. 声明function b,它会覆盖var声明
    3. 将值88赋给变量b

    所以函数实际上被转换为“逻辑等价物”:

    function a(){ 
       var b; // hoisted
       b = function b(){ // hoisted
         var c = 52; 
         console.log(c);
       } 
       console.log(typeof b); // function
       b = 88;  
       console.log(typeof b); // number 
    }
    

    注意:Only declarations are hoisted, not initializations

    【讨论】:

      【解决方案3】:

      据我所知,这不是两个不同的参考。

      在内部, function b(){/*Code Here*/} 被执行为 var b = function(){/*Code Here*/} 因此,第一个 typeof(b) 返回 function

      var b = 88; 执行时,这基本上将88 分配给b 的现有引用。 因此,第二个 typeof(b) 返回 number

      运行时映像供参考:

      【讨论】:

        猜你喜欢
        • 2012-10-27
        • 2011-04-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-06
        • 1970-01-01
        相关资源
        最近更新 更多