Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
491 views
in Technique[技术] by (71.8m points)

javascript - Function hoisting in js

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...