Question

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();

I am not able to understand how the hoisting works in this case and why alert("local mysecondmethod"); is not shown. If someone can show me the sequence it would be helpful

Était-ce utile?

La solution

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.

Autres conseils

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();
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top