JavaScript重载回调 [英] JavaScript overloading with a callback
本文介绍了JavaScript重载回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
按照此问题中推荐的模式,我们有类似的东西到:
Following the pattern recommended in this question, where we have something akin to:
function foo(a, b, opts) {
}
foo(1, 2, {"method":"add"});
foo(3, 4, {"test":"equals", "bar":"tree"});
那么如何将回调包含为最终参数呢?我有函数 foo()
,应该能够处理两个:
How would one then include a callback as the final parameter? I have function foo()
that should be able to handle both of:
foo(x, y, function() {
// do stuff
});
和
foo(x, y, z, function() {
// do stuff
});
有任何建议吗?
推荐答案
结束使用以下解决方案:
Ended up going with the following solution:
foo(args) {}
foo({"x":"add", "callback": function() {
// do stuff
}});
foo({"x":"equals", "y":"tree", "callback": function() {
// do stuff
}});
然后只需检查最后一个参数值是否为函数,ala @ PaulP.RO' s的解决方案:
And then simply checking to see if the last arguments value is a function, ala @PaulP.R.O.'s solution above:
if((arguments.length > 1) && (typeof arguments[arguments.length - 1] === 'function')) {
var callback = arguments[arguments.length - 1];
}
这篇关于JavaScript重载回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文