2011-08-08 56 views
1

我將一個回調函數作爲參數傳遞給一個函數,我在我的web應用程序的各個部分執行此操作。當傳遞一個回調函數時,你可以設置一個參數嗎?

我希望回調在某些情況下反應有點不同,我可以通過某種方式將參數傳遞給此回調嗎?

soemethod(callback); 
otherethod(callback); 

otherother(callback(a=1)); 

如何在回調中傳遞a = 1?

回答

4

只需用匿名函數在你的參數的函數調用包裝:

otherother(function() { 
    callback(1); // assuming the first parameter is called a 
}); 
0

不,你不能。

但你可以做這樣的事情:

soemethod(callback); 
    otherethod(callback); 

    otherother(callback, 1); 


function otherother(callback, defaultValue) { 
    var value = defaultValue; 

    // your logic here, ie. 
    if(someCondition) 
     value = 2; 

    callback(value); 
} 
0

正如其他人已經提到的,你不能傳遞默認參數就像在Javascript中 - 你必須自己創建單獨的函數。

可以但是,使用一些非常整齊的幫助函數爲你自動創建這些閉包。我最喜歡的模式之一是partial function application,其中「默認」參數是最左邊的參數。

如果您正在使用新的瀏覽器可以使用Function.prototype.bind(它也處理this參數 - 這可以允許通過方法的回調以及)

otherother(callback.bind(undefined, 1)); 
//sets the first parameter to 1 
//when the callback is called, the 2nd, 3rd, parameters are filled and so on 

如果您需要支持舊的瀏覽器爲好, create your own部分應用功能並不難(大量的JS框架有某種類型,下一個例子取自原型)

Function.prototype.curry = function() { 
    var fn = this, args = Array.prototype.slice.call(arguments); 
    return function() { 
     return fn.apply(this, args.concat(
     Array.prototype.slice.call(arguments))); 
    }; 
    }; 
Function.prototype.curry = function() { 
    var fn = this, args = Array.prototype.slice.call(arguments); 
    return function() { 
     return fn.apply(this, args.concat(
     Array.prototype.slice.call(arguments))); 
    }; 
    }; 
相關問題