遵循 this question 中推荐的模式,其中我们有类似于:
function foo(a, b, opts) {
}
foo(1, 2, {"method":"add"});
foo(3, 4, {"test":"equals", "bar":"tree"});
然后如何将回调作为最终参数包含在内?我有函数 foo()
应该能够处理:
foo(x, y, function() {
// do stuff
});
和
foo(x, y, z, function() {
// do stuff
});
有什么建议吗?
最佳答案
所以基本上你想接受可变数量的参数,然后是最后一个回调?类似于 PHP 的 array_udiff
有用吗?
这很简单:
function foo() {
var args = [], l = arguments.length, i;
for( i=0; i<l; i++) args[i] = arguments[i];
var callback = args.pop();
// now you have your variable number of arguments as an array `args`
// and your callback that was the last parameter.
}
关于使用回调重载 JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9831027/