【问题标题】:Function hoisting in jsjs中的函数提升
【发布时间】:2013-04-19 08:18:20
【问题描述】:
function mymethod(){
  alert("global mymethod");
}

function mysecondmethod(){
  alert("global mysecondmethod");
}

function hoisting(){
  alert(typeof mymethod);
  alert(typeof mysecondmethod);

  mymethod();         // local mymethod
  mysecondmethod(); // TypeError: undefined is not a function

  // mymethod AND the implementation get hoisted
  function mymethod(){
    alert("local mymethod");  
}

// Only the variable mysecondmethod get's hoisted
var mysecondmethod = function() {
    alert("local mysecondmethod");  
};
}
hoisting();

我无法理解在这种情况下提升是如何工作的,以及为什么没有显示 alert("local mysecondmethod");。如果有人可以告诉我顺序会很有帮助

【问题讨论】:

    标签: javascript hoisting


    【解决方案1】:

    理解提升的最简单方法是获取所有 var 语句并将它们移动到包含它们的函数的顶部:

    function hoisting(){
      var mysecondmethod; // locally undefined for now
      alert(typeof mymethod);
      alert(typeof mysecondmethod);
    
      mymethod();         // local mymethod
      mysecondmethod(); // TypeError: undefined is not a function
    
      // mymethod AND the implementation get hoisted
      function mymethod(){
        alert("local mymethod");  
      }
    
      // Only the variable mysecondmethod get's hoisted
      mysecondmethod = function() {
        alert("local mysecondmethod");  
      };
    }
    hoisting();
    

    【讨论】:

      【解决方案2】:

      在您的 hoisting 函数中,代码重新排序如下:

      function hoisting(){
        var mysecondmethod;
      
        function mymethod(){
          alert("local mymethod");  
        }
      
        alert(typeof mymethod);
        alert(typeof mysecondmethod);
      
        mymethod();
        mysecondmethod();
      
      
        mysecondmethod = function() {
          alert("local mysecondmethod");  
        };
      }
      

      这里很明显,您在函数范围内创建了一个新变量mysecondmethod,它覆盖了您的外部定义。 然而,在调用函数的时候,它还没有被定义,因此你会得到你的错误。

      【讨论】:

      • 这有帮助。您的代码还解释了为什么打印 local mymethod 而不是全局的。谢谢。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-06
      • 2017-04-02
      • 2018-06-09
      相关资源
      最近更新 更多