In Actionscript 3 I could add a method to an object dynamically. like to below code
var s:Sprite = new Sprite()
var f:Function = function(){this.graphic.clear()}
s.clean = f
could I create another Sprite instance with the clean function from s ?
It is possible using the prototype of Sprite :
Sprite.prototype.clean = function():void { trace("works"); }
var s1:Sprite = new Sprite();
var s2:Sprite = new Sprite();
s1["clean"]();
s2["clean"]();
Of course this adds clean to all the instances of Sprite you create, if that's not what you want you could just create a function to create sprites and use that.
function createSprite():Sprite
{
var s:Sprite = new Sprite();
var f:Function = function(){this.graphic.clear()}
s.clean = f ;
return s;
}
If you don't want to alter the Sprite class your other option is inheritance and adding the clean method to this new class :
public class MySprite extends Sprite
{
public function clean():void
{
this.graphic.clear();
}
}
var s1:MySprite = new MySprite();
s1.clean();