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)

3
  • 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. Commented Aug 11, 2009 at 18:51
  • Congratulations, you are already #3 result on google under "actionscript argument unpacking" :) Commented Aug 12, 2009 at 11:51
  • Good lord. SO.com really must be doing well, mm? Commented Aug 12, 2009 at 15:05

1 Answer 1

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.

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

2 Comments

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 ...
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.

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.