Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript overloading with a callback

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"});

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
});

And

foo(x, y, z, function() {
  // do stuff
});

Any suggestions?

like image 217
Unpossible Avatar asked Apr 24 '26 17:04

Unpossible


1 Answers

So basically you want to accept a variable number of arguments, followed by a callback as the last one? Something similar to how PHP's array_udiff works?

This is fairly simple:

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.
}
like image 181
Niet the Dark Absol Avatar answered Apr 26 '26 05:04

Niet the Dark Absol



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!