JavaScript 提升函数 vs 函数变量

JavaScript hoisting function vs function variable

这是我的 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 is not defined 的错误。

函数表达式

  var b = function(){
        console.log("B is called");
    }

函数声明:

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

Function Expressions 仅在解释器到达 code.On 函数 Declaration 的那一行时加载,它'总会工作的。因为在加载所有声明之前无法调用任何代码。

阅读更多关于 Function Declaration and Function Expression

您调用时 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");
 }

KISSJavaScript

因为使用函数表达式声明函数会创建匿名函数,除非您明确提供名称:

var b = function() {}   // anonymous function 

不同的是,当你使用函数声明声明一个函数时,你设置了一个名称:

function c() {}   // c function