Flash AS3: automate property assignment to new instance from arguments in constructor

Posted by matt lohkamp on Stack Overflow See other posts from Stack Overflow or by matt lohkamp
Published on 2010-04-08T21:00:32Z Indexed on 2010/04/08 21:03 UTC
Read the original article Hit count: 244

Filed under:
|
|
|
|

I like finding out about tricky new ways to do things. Let's say you've got a class with a property that gets set to the value of an argument in the constructor, like so:

package{
 public class SomeClass{
  private var someProperty:*;
  public function SomeClass(_someProperty:*):void{
   someProperty = _someProperty;
  }
 }
}

That's not exactly a hassle. But imagine you've got... I don't know, five properties. Ten properties, maybe. Rather then writing out each individual assignment, line by line, isn't there a way to loop through the constructor's arguments and set the value of each corresponding property on the new instance accordingly? I don't think that the ...rest or arguments objects will work, since they only keep an enumerated list of the arguments, not the argument names - I'm thinking something like this would be better:

for(var propertyName:String in argsAsAssocArray){this[propertyName] = argsAsAssocArray[propertyName];}

... does something like this exist?

© Stack Overflow or respective owner

Related posts about flash

Related posts about actionscript-3