Function hoisting in js

后端 未结 2 728
失恋的感觉
失恋的感觉 2020-12-21 17:13
function mymethod(){
  alert(\"global mymethod\");
}

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

function hoisting(){
  alert(typeof mymethod)         


        
相关标签:
2条回答
  • 2020-12-21 17:57

    Inside your hoisting function the code gets reordered as follows:

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

    Here it is pretty obvious, that you create a new variable mysecondmethod inside the function's scope, which overlays your outside definition. At the point of the call of the function, however, it is not defined (yet) and thus you get your errors.

    0 讨论(0)
  • 2020-12-21 17:59

    The simplest way to understand hoisting is to take all var statements and move them to the top of the function containing them :

    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();
    
    0 讨论(0)
提交回复
热议问题