Skip to content Skip to sidebar Skip to footer

Function Hoisting In Js

function mymethod(){ alert('global mymethod'); } function mysecondmethod(){ alert('global mysecondmethod'); } function hoisting(){ alert(typeof mymethod); alert(typeof my

Solution 1:

Inside your hoisting function the code gets reordered as follows:

functionhoisting(){
  var mysecondmethod;

  functionmymethod(){
    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.

Solution 2:

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

functionhoisting(){
  var mysecondmethod; // locally undefined for nowalert(typeof mymethod);
  alert(typeof mysecondmethod);

  mymethod();         // local mymethodmysecondmethod(); // TypeError: undefined is not a function// mymethod AND the implementation get hoistedfunctionmymethod(){
    alert("local mymethod");  
  }

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

Post a Comment for "Function Hoisting In Js"