简体   繁体   中英

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.)

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?

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM