Instantiate and Set Properties

  1. function create(obj:Class, props:Object):*{
  2.     var o:* = new obj();
  3.     for (var p:String in props){
  4.         o[p] = props[p];
  5.     }
  6.     return o;
  7. }
  9. // test out the function
  11. var txt:TextField = create(TextField, {x:200, y:100, selectable:false, text:"hello there", textColor:0xFF0000, defaultTextFormat:new TextFormat("_sans", 20)});
  12. addChild(txt);
  14. var s:Sprite = Sprite(addChild(create(Sprite, {x:100, y:100, rotation:45, alpha:.5})));
  16. with ( beginFill(0xFF0000), drawRect(-20,-20,40,40);
  18. var blur:BlurFilter = create(BlurFilter, {blurX:2, blurY:8, quality:1});
  20. s.filters = [blur];

This snippet shows a function called create() that takes two arguments. The first argument is the name of a class to instantiate. The second is an Object with a list of properties to set on a newly created instance of the class (referenced in the first argument).

This could be particularly useful for TextFields which for some reason have no arguments in their constructor.

This will currently only work for classes that have either all optional constructor arguments or no constructor arguments.

This entry was posted in dynamic, functions, one-liners, properties and tagged , . Bookmark the permalink. Both comments and trackbacks are currently closed.