Function hoisting in js

安稳与你 提交于 2019-11-29 17:07:29

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.

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();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!