在函数内部实现回调函数

时间:2014-10-22 09:18:20

标签: javascript callback jquery-callback

假设我有以下功能。

loadXML('Method', requestString, function(callback){
   // The function as a callback parameter to loadXML goes here.

   // Here I am calling the callback function like this       
   if(callback != null){
       callback();
   }
});

但是我想在loadXML函数中定义这个回调函数。我可以这样做吗?

loadXML('Method', requestString, function(callback){
   // The function as a callback parameter to loadXML goes here.

   // Here I have to call the callback function like this, (do I?) which is a 
   // callback parameter to callback function of loadXML
   callback = function(){
       // The callback function implementation goes here
   }
});

1 个答案:

答案 0 :(得分:1)

也许这可以帮助您理解嵌套的回调机制:

var loadXML;
var outerCB;
var innerCB;     

loadXML = function(method, requestString, cb) {
  // pass the innerCB implementation as argument to the outer cb
  if('undefined' !== typeof innerCB) {
    cb(innerCB);
  } else {
    // in case innerCB would not be defined
    cb(function() {
      console.log('hi from anonymous cb')
    });
  }
};


innerCB = function() {
  console.log('hi from innerCB cb!')
};

outerCB = function(callback) {
  if('undefined' !== typeof callback) {
    callback(); // innerCB();    
  } else {
    console.log('no cb passed, do something else')
  }    
}

loadXML('Method', 'abcd', outerCB) // hi from innerCB cb!