[英]Passing parameter in callback
I would like to be able to pass a parameter in a callback, but from the original calling function, and with the stipulation below, eg given: 我希望能够在回调函数中传递参数,但是要从原始调用函数传递参数,并具有以下规定,例如:
function foo() {
var p = 5;
getDataFromServer(callBackFunction);
}
function callBackFunction(data) {
// I need value of 'p' here
...
}
function getDataFromServer(callback) {
// gets data from server
callback.call();
}
The catch is that I don't want to change the function getDataFromServer(), (ie allowing it to accept another parameter.) 问题是我不想更改函数getDataFromServer() (即允许它接受另一个参数)。
Is this possible? 这可能吗? Thanks.
谢谢。
Yes, you could use a closure to do this. 是的,您可以使用闭包来执行此操作。
However, it's hard to give code for this because your example isn't clear. 但是,由于您的示例不清楚,因此很难给出代码。
My guess is that you want something like this: 我的猜测是您想要这样的东西:
function foo() {
var p = 5;
getDataFromServer(callBackFunction(p));
}
function callBackFunction(p) {
var closureOverP = function(data) {... something with p ...};
return closureOverP;
}
Yes, and this is good to know. 是的,这很高兴知道。
function foo() {
var p = 5;
getDataFromServer(function(){
callBackFunction(p)
});
}
So a simple anon function won't do? 那么一个简单的anon函数不会起作用吗?
function foo()
{
var p = 5;
getDataFromServer( function()
{
callBackFunction( p );
} );
}
It's Definitely possible and I would say good practice with functional programming languages. 绝对有可能,我会说功能编程语言的良好实践。 But you call the function like this:
但是您可以这样调用函数:
function getDataFromServer(callback) {
// gets data from server
callback();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.