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");没有显示。如果有人能给我看一下序列会很有帮助
发布于 2013-04-25 20:31:00
在hoisting函数中,代码按如下方式重新排序:
function hoisting(){
var mysecondmethod;
function mymethod(){
alert("local mymethod");
}
alert(typeof mymethod);
alert(typeof mysecondmethod);
mymethod();
mysecondmethod();
mysecondmethod = function() {
alert("local mysecondmethod");
};
}这里很明显,您在函数的作用域内创建了一个新的变量mysecondmethod,它覆盖了外部定义。然而,在调用函数的时候,它还没有被定义,因此你会得到错误。
发布于 2013-04-25 20:29:55
理解提升的最简单方法是获取所有var语句,并将它们移到包含它们的函数的顶部:
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();https://stackoverflow.com/questions/16214724
复制相似问题