Seanonymous
Seanonymous

Reputation: 1384

In AS3, how would I pass the contents of an object as arguments for a function?

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?

Upvotes: 2

Views: 1063

Answers (4)

NoobsArePeople2
NoobsArePeople2

Reputation: 1996

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:

var myObject:Object = { command: doSomething, args: [ "dog", 11, myArray ] };

Where command is a reference to the Function to be called and args is the list of arguments that command requires. Then, to call the doSomething:

myObject.command.apply(this, myObject.args)

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 command and args in myObject. 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.

Upvotes: 2

Jeremy
Jeremy

Reputation: 3538

EDIT: Right I've now added another method that can take any number of arguments, in any form. It will essentially give you an Array of parameters to handle.

private var _testObject:Object;

private function init():void{
    _testObject = {str:"test", num:11, arr:["test","array"]};
    doSomething(_testObject.str, _testObject.num, _testObject.arr);
}

private function doSomething(...args):void{
    trace(args.toString());
}

Of course that will need to be inside a class or a script tag, but if you call the init method you should see the following trace: test,11,test,array

Hope that helps.

Upvotes: 0

zaynyatyi
zaynyatyi

Reputation: 1116

You should pass your object values as

var args:Object = { a:'dog', b:11, c:myArray };
function doSomething( args.a, args.b, args.c );

Upvotes: 0

Ross Smith
Ross Smith

Reputation: 755

Are you a Python developer? ;)

You have to turn your args:Object into an args:Array and then call doSomething.apply(this, argsArray). The trouble here is that your arguments in the args:Object are not ordered, and thus looping over them to turn them into an Array to pass to apply() will not result in a predictable sequence of arguments.

Unless you have a strategy to enforce the correct order of properties in the Object-to-Array conversion, it sounds like a no go.

Upvotes: 5

Related Questions