在Javascript中如何在回调上传递变量大小的参数是否有灵活而通用的方法?
var myCallback = function (param1, param2){
...
};
var myOtherCallback = function (param1, param2, param3){
...
};
var func = function(callback, callbackParams){
// how can I put the values on callbackParams as the actual callback parameters down here?
callback( /* callbackParams */ );
};
func(myCallback, [myparam1, myparam2]);
func(myOtherCallback, [newparam1, newparam2, newparam3]);
答案 0 :(得分:1)
您可以在函数中使用spread operator。 话虽这么说,我的例子中没有看到任何回调用途。我假设你故意简化你的问题,向我们解释。
var myCallback = function (param1, param2){
...
};
var myOtherCallback = function (param1, param2, param3){
...
};
var func = function(callback, callbackParams){
// how can I put the values on callbackParams as the actual callback parameters down here?
callback(...callbackParams);
};
func(myCallback, [myparam1, myparam2]);
func(myOtherCallback, [newparam1, newparam2, newparam3]);
答案 1 :(得分:0)
我找到了我要找的东西......
var myCallback = function (param1, param2){
console.log("myCallback", param1, param2)
};
var myOtherCallback = function (param1, param2, param3){
console.log("myCallback", param1, param2, param3)
};
var func = function(callback){
var additionalParams = Array.prototype.slice.call(arguments, 2);
callback.apply(this, additionalParams);
};
func(myCallback, "myparam1", "myparam2");
func(myOtherCallback, "newparam1", "newparam2", "newparam3");
虽然对于更现代的方法,Kuu Aku的答案可能会更好