2013-04-25 35 views
1
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");未显示。如果有人可以告诉我的顺序将是有益的js中的功能吊装

回答

2

里面你hoisting功能该代码被重新排序如下:

function hoisting(){ 
    var mysecondmethod; 

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

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

    mymethod(); 
    mysecondmethod(); 


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

这是很明显的,您创建一个新的变量mysecondmethod功能的范围,其覆盖的外定义中。 然而,在函数调用的时候,它还没有被定义,因此你会得到你的错误。

+0

这有助于。你的代码也解释了为什么'本地mymethod'被打印而不是全局打印。谢谢。 – dazzle 2013-04-25 12:38:39

1

了解吊装最简单的方法是采取一切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();