遵循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 - 带有回调的JavaScript重载,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9831027/

10-10 00:43
查看更多