2012-04-13 130 views
0

我有兩個功能,通過一則作爲參數,如:傳遞函數的參數

var a = function(f) 
{ 
    // some code 
    f(); 
}; 

var b = function() 
{ 
}; 

a(b); // works great, the function a is executed, then the function b is executed 

現在我需要把它擴大到樹的功能,如:

var a = function(f) 
{ 
    // some code 
    f(); 
}; 

var b = function(f) 
{ 
    // some code 
    f(); 
}; 

var c = function() 
{ 
}; 

a(b(c)); // but it does not work. b(c) words like a method and get executed right on the instruction. 

哪有我去做?

回答

2

這聽起來像你想使用一個回調一種模式。而不是簡單地沿着功能結果傳球,你會做一些像這樣:

var a = function(callback) 
{ 
    // Do Stuff 
    callback(); 
} 

var b = function(callback) 
{ 
    // Do Stuff 
    callback(); 
} 

var c = function() { } 

你的代碼最終會看起來像這樣:

a(function() 
{ 
    b(function() 
    { 
     c(); 
    }); 
}); 

實際上,你沿着另一個函數來執行通該方法完成後。在上面的場景中,我僅僅提供了兩個匿名函數作爲回調參數。

3

傳遞執行b(c)包裝函數:

a(function() { 
    b(c); 
}); 
1
function a(f){ 
    // code 
    f() 
} 
function b(f){ 
    // code 
    a(f()) 
} 
function c(){ 
    //code 
} 

b(c); 
1

的一種方法是使用匿名函數:

a(function() { b(c); });