For example, I have a function:
function doSomething( a:String, b:Number, c:Array ):void {
trace( a + b + c.toString() );
}
…and I have an object that has all the elements I would want to pass arguments:
var args:Object = { 'dog', 11, myArray };
…and I want to be able to pass the contents of args to doSomething without making any changes to doSomething (assume it’s someone else’s function) and I’d like to do it in a way that doesn’t assume I will know anything about the contents of args.
Is this possible?
What you want to use is Function.apply(). To do this you will need to change the ‘args’ Object from your example to an Array.
Then you would construct objects like:
Where
commandis a reference to the Function to be called andargsis the list of arguments thatcommandrequires. Then, to call thedoSomething:As an added bonus this will work with any function with any number of arguments, all you need to do is change the values for
commandandargsinmyObject. So you could pass in a list of objects that conform to these rules and loop over them without having to change any of this code.