这是我的JavaScript代码:

    console.log(a);
    c();
    b();
    var a = 'Hello World';
    var b = function(){
        console.log("B is called");
    }
    function c(){
        console.log("C is called");
    }


现在这里输出:

undefined
hoisting.html:12 C is called
hoisting.html:6 Uncaught TypeError: b is not a function


我的问题是关于c()和b()为什么表现不同。并且b应该引发错误,例如未定义b。

最佳答案

功能声明将与其主体一起悬挂。

不是函数表达式,只有var语句将被挂起。



这是您的代码在编译时间之后-运行时之前的样子“像”解释器的样子:

 var c = function c(){
      console.log("C is called");
 }

 var a = undefined
 var b = undefined

 console.log(a); // undefined at this point
 c(); // can be called since it has been hoisted completely
 b(); // undefined at this point (error)

 a = 'Hello World';
 b = function(){
     console.log("B is called");
 }


吻JavaScript

09-25 18:07
查看更多