5

I need to call a varargs function:

function doSomething(... args): Object {
    // do something with each arg
}

However, I'm building the arguments for this dynamically:

var someArgs: Array = ['a', 'b', 'c'];
doSomething(someArgs);

The problem is, when I call the function in this way args ends up being a 1-element array with someArgs as the first element, not a three-element array.

How can I call doSomething with someArgs as the argument array?

(For the search engines, this is argument unpacking)

Chris R
  • 17,546
  • 23
  • 105
  • 172
  • 1
    Note: this is called "argument unpacking". If you search google for that term as well as actionscript you will find a few discussions on the matter. Brian's suggestion to use .apply is correct IMO. – James Fassett Aug 11 '09 at 18:51
  • Congratulations, you are already #3 result on google under "actionscript argument unpacking" :) – Rydell Aug 12 '09 at 11:51
  • Good lord. SO.com really must be doing well, mm? – Chris R Aug 12 '09 at 15:05

1 Answers1

9

Use Function.apply.

Like this:

doSomething.apply(null, someArgs);

If doSomething is a method of a class, pass in the class instead of null.

Brian
  • 752
  • 6
  • 10
  • 1
    actually, it does not matter, whether you pass in the class/instance ... AS3 automatically creates method closures, where "this" is preassigned to always be the owner of the method ... – back2dos Aug 11 '09 at 18:49
  • I ended up finding this about ten minutes after posting. I figured I'd still provide rep to whomever answered, and it's nice to have it on SO.com. – Chris R Aug 11 '09 at 20:49