My friend Alan and I had talked about this about 6 months ago. Suppose that you want to have an AS 2.0 Class that extends MovieClip, and you would like to “instantiate” as a movieclip in some location in your flash movie. It would be great to be able to call that class in the same way that you can call MovieClip.createEmptyMovieClip(), and have a new movieclip instance that is in fact, a class that extends MovieClip.
Originally, the way that I had been doing this was to first create a class that extends MovieClip such as this ::
[as]class com.plasticstare.SpaceInvader extends MovieClip { function SpaceInvader():Void{ trace(“All your base…”); } } [/as]
Then, I would create an empty movieclip symbol in the library of my .fla file, and give it a linkage id, and then in the linkage associate it with the AS 2.0 class of my choosing, or in this case, com.plasticstare.SpaceInvader.
There are a few problems with this beyond the fact that it seems a bit laborious to have to do this. When compiling code in MTASC, for example, you have to create a special little class to make sure that any .swfs that you are publishing as shared libraries actually get the newly compiled code and make a reference to it in your .fla files (or there is probably some other way to do this as well). Otherwise, if you make a change to your class for that linked symbol, you have to publish back out of the Flash IDE again. (And if you have a bunch of them, its a real pain.)
I stumbled upon another way of doing this today when checking out something else in the Flash LiveDocs. Someone had contributed the code below in its original form, and I’ve since made a couple of tweeks – one to fix a major flaw.
[as]public function createExtendedMovieClip(_constructor:Function, _parent:MovieClip, _depth:Number) { if (!_parent) { _parent = _root; } if (!_depth) { _depth = _parent.getNextHighestDepth(); } var mc:MovieClip = _parent.createEmptyMovieClip(“clip_”+_depth, _depth); var obj:Object = new _constructor(); for (var i in obj) { mc[i] = obj[i]; } mc.constructor = _constructor; mc.__proto__ = obj.__proto__; return mc; } [/as]
The idea would be to use this in your Main.as class or some utility class — some class that you can reach universally. So, supposed that I have it in my Main singleton class. I would call the function this way
Main.getInstance().createExtendedMovieClip(SpaceInvader,_root);
in order to create a new SpaceInvader clip in the _root. _constructor is simply the name of the class that you want to instantiate, and _parent and _depth are the clip you want it to reside in and at what depth. (the latter 2 parameters as you see are optional) Using this code, you can just create any new Class that extends MovieClip and instantiate it as a MovieClip instance on the stage on the fly, without creating any special linked symbols in the library.