功能在js中提升 [英] Function hoisting in js

查看:80
本文介绍了功能在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();

我无法理解吊装在这种情况下是如何工作的以及为什么 alert(local mysecondmethod); 未显示。如果有人可以告诉我这个顺序会有所帮助

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

推荐答案

在你的中提升函数代码按如下方式重新排序:

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");  
  };
}

很明显,你创建了一个新变量 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.

这篇关于功能在js中提升的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆