2013-04-25 30 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();