【问题标题】:JavaScript hoisting function vs function variableJavaScript 提升函数 vs 函数变量
【发布时间】:2016-02-07 12:19:05
【问题描述】:

这是我的 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 未定义的错误。

【问题讨论】:

标签: javascript hoisting


【解决方案1】:

函数声明将连同它的主体一起被提升。

不是函数表达式,只会提升 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

【讨论】:

  • 谢谢。我添加了 console.log(b) & console.log(c) 语句来验证你的答案。而且你很准。谢谢
【解决方案2】:

函数表达式

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

功能声明

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

Expressions 函数仅在解释器到达该行代码时加载。另一方面,Declaration 函数始终有效。因为在加载所有声明之前无法调用任何代码。

阅读更多关于Function DeclarationFunction Expression的信息

【讨论】:

    【解决方案3】:

    在您调用 b 时尚未定义。您的 b 是一个包含函数的变量,您访问 b 的时间尚未定义。

    【讨论】:

      【解决方案4】:

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

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

      当你用函数声明声明一个函数时,你设置了一个名称:

      function c() {}   // c function 
      

      【讨论】:

        猜你喜欢
        • 2015-03-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-01
        • 2016-03-14
        • 1970-01-01
        • 1970-01-01
        • 2011-06-21
        相关资源
        最近更新 更多