如何将其他参数传递给回调并访问默认参数?

假设我将此作为jQuery小部件的选项:

function oneFunc() { var myVar; //there is some widget calling $.widget("ui.combobox", $.ui.autocomplete, { options: { source: function (request, response){////doing something with myVar, request and response} } }); } 

现在我想使用回调分离出function (request, response)

所以,我想要这样的东西:

 function oneFunc() { var myVar; //there is some widget calling $.widget("ui.combobox", $.ui.autocomplete, { options: { source: myCallBack }); } function myCallBack(request, response){ //I can get request and response here by default but not myVar //doing something with myVar, request and response } 

所以,我无法访问myVar。 我必须把它传递给那里。 但是怎么做?

编辑:我不想使用全局变量requestresponse是我可以在myCallBack中获得的默认值。

如果可以避免匿名function,那就更好了。

您可以使用Function.applyFunction.call来完成此操作

 function oneFunc(myCallback) { this.myVar = 1; var request = "request"; var response = "response" //there is some widget calling myCallback.apply(this,[request,response]); } function callback(request, response){ console.log(request); console.log(response); console.log(this.myVar); } oneFunc(callback); 

以上输出

 request response 1 

因为您已将this关键字委托给回调方法,允许它访问原始方法中声明的任何变量。

实例: http : //jsfiddle.net/hFsCA/

注意apply行也可以替换为(Thanks @AlessandroVendruscolo)

 myCallback.call(this,request,response); 

并不是说它有太大的区别 – 但是为了完整性!

所以将它包装回你的(现在更新的)示例中:

 function oneFunc(callback) { this.myVar = 1; var self = this; //there is some widget calling $.widget("ui.combobox", $.ui.autocomplete, { options: { source: function (request, response){ callback.call(self,request,response); } } }); } 

如果你想在你的单独的回调函数中访问myVar ,我会在声明中明确它:

 function myCallBack(request, response, myVar) { } 

这样可以更轻松地跟踪以后在代码中看到它的时间。 然后,你编写这样的代理函数:

 source: function(request, response) { return myCallBack.call(this, request, response, myVar); } 

如果您想要更复杂的范围或者需要在两个范围中更改myVar ,则需要一个对象:

 var myScope = { myVar: null }; // ... source: function(request, response) { return myCallBack.call(this, request, response, myScope); } 

然后,在回调内:

 function myCallBack(request, response, myScope) { // use myVar as myScope.myVar } 

如果jQuery内部使用任何匿名函数,我不会。 但我解决了这个问题:

 function oneFunc() { var myVar; //there is some widget calling $.widget("ui.combobox", $.ui.autocomplete, { options: { source: $.proxy(myCallBack, this, myVar) }); } function myCallBack(myVar, request, response){ //I can access myVar, request and response //doing something with myVar, request and response } 

我猜其他有经验的人可以对此发表评论。