2014-10-22 66 views
0

說我有一個像下面這樣的函數。在函數內部實現回調函數

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 
    } 
}); 
+0

我認爲'callback'是一個參數'的loadXML()',而不是通過其他任何地方。你嘗試過'console.log(arguments);'函數內部嗎? – 2014-10-22 09:22:10

+1

爲什麼要定義一個函數然後不使用它?如果你沒有把它傳遞到函數中,它實際上並不是一個回調函數。你究竟在努力實現什麼? – Quentin 2014-10-22 09:28:02

+0

還有一個loadXML()的回調函數,它定義在那裏,我希望有另一個函數的回調函數。然後讓我更新代碼。 – vidulaJ 2014-10-22 09:28:39

回答

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! 
+0

Thanx Villiam。我會去這個&試試這個。 – vidulaJ 2014-10-22 14:56:54