回调函数如何传参?

2018-10-31  本文已影响260人  ThomasYoungK

我有一个带参数的callback,如何把参数传递给callback呢?

// callback function
function tryMe (param1, param2) { 
    alert (param1 + " and " + param2); 
} 

我从stackoverflow中看到几个非常漂亮的答案:https://stackoverflow.com/questions/3458553/javascript-passing-parameters-to-a-callback-function
法一:在callback函数tryMe外面封装一个无参的匿名函数,在匿名函数内部显示调用参数:

// callback function
function tryMe (param1, param2) { 
    alert (param1 + " and " + param2); 
} 

// callback executer 
function callbackTester (callback) { 
    callback(); 
} 

// test function
callbackTester (function() {
    tryMe("hello", "goodbye"); 
}); 

法二:类似法一,不过匿名函数保留一个参数,供调用函数callbackTester在调用匿名函数时,由callbackTester决定传什么参数进去。

// callback function
function tryMe (param1, param2, param3) { 
    alert (param1 + " and " + param2 + " " + param3); 
} 

// callback executer 
function callbackTester (callback) { 
//this is the more obivous scenario as we use callback function
//only when we have some missing value
//get this data from ajax or compute
var extraParam = "this data was missing" ;

//call the callback when we have the data
    callback(extraParam); 
} 

// test function
callbackTester (function(k) {
    tryMe("hello", "goodbye", k); 
}); 
上一篇下一篇

猜你喜欢

热点阅读