9

I need to pass arguments onto a callback function as real arguments. How do I do that? callback requires a variable number of arguments.

Example function like this:

var func = function (callback) {
  doSomething(function () {
    // the goal is to pass on the arguments object to the callback function as real arguments
    callback(arguments)
  });
}

Thanks in advance.

It might be a similar question to this: Is it possible to send a variable number of arguments to a JavaScript function?

But I didn't understand that question nor the answers.

Edit: If possible, I would like to not pollute global.

1 Answer 1

18

Use apply to invoke the callback so the array items gets passed as individual arguments to the function.

callback.apply(this, arguments);

apply takes the context, and an array as an argument, and each item of the array can be passed as a named argument of the function being invoked.

function two(first, second) {
    alert(first), alert(second);
}

two.apply(null, ["Hello", "World"]); // alerts "Hello", then "World"

Implementations of ES3 required that the second argument to apply be either an array, or an arguments object. ES5 makes it more liberal in that as long as it resembles an array - has a length property, and corresponding integer indexes, it will work.

Sign up to request clarification or add additional context in comments.

7 Comments

Why apply null instead of this?
allpy takes two arguments, the obejct which becomes this in the called function and an array whic becmes the arguments. So your line should read callback.apply(this, Array.prototype.slice.apply(arguments));
Yep, I've messed up with this before seeing your answer came up with something similar: jsfiddle.net/yahavbr/HYTJL
I'm not using this in any special manner inside the function two, so it doesn't really matter what we pass as context to apply. We could've passed in anything - two.apply("dontCare", ["Hello", "World"]).
@Hans - thanks for the correction, I'm missing the context as the first argument.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.