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
share|improve this question

3  
foo(array[0], array[1], array[2]);? – Jared Farrish Nov 24 '11 at 9:04
feedback

1 Answer

up vote 11 down vote accepted
console.log(foo.apply(null, array));
share|improve this answer
Demo: jsfiddle.net/nTeUG – Jared Farrish Nov 24 '11 at 9:08
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 Nov 24 '11 at 9:08
Demo updated: jsfiddle.net/nTeUG/1 – Jared Farrish Nov 24 '11 at 9:11
@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 Nov 24 '11 at 9:13
@Lolo That makes sense :) I changed it again. – ascii-lime Nov 24 '11 at 9:14
show 1 more comment
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.