How can I achieve the following for any number of elements in the arg
array? If it was a function, I'd use Function.apply(), but I can't figure out how to do it with the new
operator.
var arg:Array = [1,2];
new MyClass( arg[0], arg[1] );
How can I achieve the following for any number of elements in the arg
array? If it was a function, I'd use Function.apply(), but I can't figure out how to do it with the new
operator.
var arg:Array = [1,2];
new MyClass( arg[0], arg[1] );
Dont pass each element of the array, just pass the array.
var arg:Array = [1,2];
new MyClass(arg);
Then inside of your class, loop through the array.
If you set up your class to accept a list of arguments using ... args
you can pass in as many as you like. Then in the constructor you will access them just like a normal array.
class MyClass
{
public function MyClass(... args):void
{
//args is an Array containing all the properties sent to the constructor
trace(args.length);
}
}
It is unfortunately not possible, because there is no way to directly access the constructor method of a Class object.
Note: If you'd be using a Function object to make up your class (prototype inheritance), then it would be possible, but i figure, this is not an option for you.
You could work around the problem with a little (ugly) helper method, on which you can read about here: http://jacksondunstan.com/articles/398
As stated in the comments is is not possible to apply settings on the constructor, but you could use this trick to set properties on a new instance of a class (which should be public)
public function setProps(o:Object, props:Object):* {
for (var n:String in props) {
o[n] = props[n];
}
return o;
}
.. use it like this
var args:Object = {x:1, y:2};
var instance:MyClass = setProps( new MyClass(), args ) );
source:
http://gskinner.com/blog/archives/2010/05/quick_way_to_se.html