2011-08-08 53 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))); 
    }; 
    }; 
相关问题