Back in the Flash 6 – Flash 8 world, I was a big fan of prototyping, mostly because of the limitations of MovieClip inheritance. I haven’t needed to use it at all in Actionscript 3 but I was still curious about how to accomplish it nowadays. Here’s the example I was able to create in Flex.
Sprite.prototype.spriteHelper = new SpriteHelper(); Sprite.prototype.rotateTo = function(deg:int):void{ var sh:SpriteHelper = this["spriteHelper"]; sh.target = this; sh.rotateTo(deg); } package { import flash.display.Sprite; import flash.events.TimerEvent; import flash.utils.Timer; public class SpriteHelper { public var _degreeTo:int = 0; public var _degCount:int = 0; public var _degTimer:Timer = null; public var target:Sprite; public function rotateTo(deg:int):void{ _degreeTo = deg; _degCount = 0; _degTimer = new Timer(10); _degTimer.addEventListener(TimerEvent.TIMER, doAnimateRotation); _degTimer.start(); } public function doAnimateRotation(event:TimerEvent):void{ _degCount++; if(_degCount <= 40){ target.rotation = _degreeTo * (_degCount/40); }else{ _degTimer.removeEventListener(TimerEvent.TIMER, doAnimateRotation); _degTimer = null; } } } } <mx:Box id="myContainer" backgroundColor="#FF0000" width="100" height="100" right="40" y="0" creationComplete="myContainer['rotateTo'](50)"/>
You’ll notice 2 things in the implementation here. Since Sprite is a statically defined class, accessing the prototype chain requires bracket syntax ala myContainer[‘rotateTo’](50), and secondly, most of the functionality of rotateTo has been moved into a separate class. The reason for the latter point is because accessing the prototype chain is costly, as it has to recurse through the inheritance chain until it finds the class with the property. As a result I’ve limited the prototype lookups to just spriteHelper and I move all the functionality into there.
Another thing I found in the docs is that every class creates a prototype chain by default, so merely adding prototype definitions has no effect on the creation of that object.