3

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 ?

1 Answer 1

2

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();
Sign up to request clarification or add additional context in comments.

2 Comments

I really dont want to alter the Sprite Class. Is there any prototype-style solution for that?
Edited answer, you can extend Sprite if you don't want to modify it and use that class.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.