首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >js中的函数提升

js中的函数提升
EN

Stack Overflow用户
提问于 2013-04-25 20:25:17
回答 2查看 359关注 0票数 2
代码语言:javascript
复制
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");没有显示。如果有人能给我看一下序列会很有帮助

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-04-25 20:31:00

hoisting函数中,代码按如下方式重新排序:

代码语言:javascript
复制
function hoisting(){
  var mysecondmethod;

  function mymethod(){
    alert("local mymethod");  
  }

  alert(typeof mymethod);
  alert(typeof mysecondmethod);

  mymethod();
  mysecondmethod();


  mysecondmethod = function() {
    alert("local mysecondmethod");  
  };
}

这里很明显,您在函数的作用域内创建了一个新的变量mysecondmethod,它覆盖了外部定义。然而,在调用函数的时候,它还没有被定义,因此你会得到错误。

票数 3
EN

Stack Overflow用户

发布于 2013-04-25 20:29:55

理解提升的最简单方法是获取所有var语句,并将它们移到包含它们的函数的顶部:

代码语言:javascript
复制
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();
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16214724

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档