Using Prototypes

Prototypes are one of the things that I used to completely ignore when programming in Actionscript. I guess I might have been a bit scared, because creating prototypes looked complicated. In fact, prototypes are easy-to-use and very useful.

Apart from that, using prototypes in  Actionscript is  more efficient than function objects are. See what  Adobe  has got to say about functions and prototypes:

Each function object creates two ActionScript objects, which  total 700 bytes. Creating a function object for each instance of the object can be costly in terms of memory. It is recommended to always use prototypes. Prototypes are only created once and avoid this memory overhead.

When prototypes come in handy

Generally speaking it's good to use prototypes whenever you must do many movieclip-related actions/transformation within one SWF file.  Prototypes let you easily pass the name of the movieclip that needs to be tranformed (and can be accessed as this).

Consider this example:

 

stageWidth = Stage.width;
stageHeight = Stage.height;
MovieClip.prototype.alphaIt = function() {
this._alpha = random(100)+20;
this._x = random(stageHeight)-20;
this._y = random(stageWidth)-20;
this._xscale = this._yscale=random(100)+20;
};
ball.alphaIt();
ball2.alphaIt();
ball3.alphaIt();
ball4.alphaIt();
ball5.alphaIt();

Explanation:

stageWidth = Stage.width;
stageHeight = Stage.height;

Saving the width and height values of the stage.

MovieClip.prototype.alphaIt = function() {
this._alpha = random(100)+20;
this._x = random(stageHeight)-20;
this._y = random(stageWidth)-20;
this._xscale = this._yscale=random(100)+20;
};

In these several lines of code we define a prototype function. What will it do? Well, as you can see there are several transformations, namely we're chaning alpha, xscale, x and y cordinates properties. Note "this" instead of instance name.

ball.alphaIt();
ball2.alphaIt();
ball3.alphaIt();
ball4.alphaIt();
ball5.alphaIt();

We apply the prototype function to 5 symbols.

The result:

 

 

Each time we refresh this page, the objects have different properties.


Conclusion

So, that's definetely a very cool way of programming  things in Actionscript.  Prototypes allow us to separate content from logic to a greater extent than alone functions do, hence we get a very tidy-looking code.

Average: 3.8 (10 votes)
FLA
Download FLA - Prototypes