views:

43

answers:

1

Say I have two functions that expect ...rest parameters

private function a(...myParams):void
{
    trace(myParams.length); // returns 3 parameters 1,2,3
    b(myParams);
}
private function b(...myParams):void
{
    trace(myParams.length); // returns 1 parameter (array) [1,2,3]
}

a(1,2,3);

The function a gets an array of parameters 1,2,3 but when it passes them to function b, it passes them as 1 parameter (an array containing the 3). Is there a way to pass them as 3 separate parameters instead of an array?

+2  A: 

Yes, use the apply method that all functions have (functions are objects too!). So, rather than this:

b(myParams);

You'll do this:

b.apply(this, myParams);
Branden Hall
This works, I do not understand it though?
John Isaacks
Well, in ActionScript functions are objects too. One method all functions have attached to them is called apply. This method allows you to run a function in a specified context (that's the first parameter) and with the arguments (that's the second parameter) you want. Anytime you have an array, but need to pass that array as individual arguments to a function you can use apply. IIRC this is common to all ECMAScript-based languages, such as Javascript.
Branden Hall
Thanks for the info!
John Isaacks