2

Is there a way of doing this without altering the function?

function foo(bar1, bar2, bar3)
{
    return bar1 + bar2 + bar3;
}
var array = [1, 2, 3];
console.log(foo(array)); //6
1
  • 3
    foo(array[0], array[1], array[2]);? Commented Nov 24, 2011 at 9:04

1 Answer 1

11
console.log(foo.apply(null, array));
Sign up to request clarification or add additional context in comments.

4 Comments

I don't think it makes much sense to set the this value to the function itself. Although it doesn't make any difference, I'd say setting it to e.g. null is more semantical.
@pimvdb In function this usually points to window (in browser obviously), so I guess calling foo.apply(window, array) should be the natural choice.
@Lolo That makes sense :) I changed it again.
@Lolo: If you pass null as the this value then it will be set to the window automatically. But since the this value doesn't matter null would be more meaningful - but after all it doesn't matter at all.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.