4.4.08

Assign a class to an instance

Phatness



So its been a while since I've posted anything. My new job has been keeping me really busy. I thought I would write about Object.registerClass and talk about how I am using __proto__ to allow a class to become a specific target.

For seasoned veterans this is probably a part of your AS2 library of tricks. Until recently I had become accustomed to using Object.registerClass to accomplish this. The process was pretty straight forward.

1. Register the library item
2. Attach the clip
3. Un-register the library item (so that we don't later inadvertently re-attach an instance of the class in a later call)




This works great for instantiating a new instance of a class without having to link a library item explicitly at design-time and it allows you to attach classes anywhere at will during run-time. But you have to make sure that every swf has "_blank" in its library and you can never instantiate as instance of a class at the root. There are other drawbacks which I wont go into here.

Introducing the super handy "register" function. You can name your function anything you like: ("infect","control","become","instantiateAs" etc...) you dont need any library items, no design time links, and so on and so on.



Of course you want to replace MyClass with your actual class name and its probably a good idea to create a "main" function or something to run your initialization code from. The register function is static so you wont have an instance of this, just call target.main() and create a non-static function in your class. Then to register a target as a specific class you just call its register function and pass it a target.



This one line of code will even instantiate _level0, (Yes, _root) as your class, now for AS2, that is about as good as it gets.

No comments: