Dynamically constructing class in AS2.0
When would you want to dynamically create a class? You want to do it when you aren't sure at compile-time what class you want to instantiate. For example, different levels of your games might have different types of characters, and you want the ability to read in an XML file that specifies what character class you should instantiate.
For example, in level 1, you may want to do this:
var hero = new Dragoon();
level 2, you want to do this:
var hero = new Zealot();
Wouldn't it be nice if this is determined at run-time (e.g. via XML)?
You can dynamically create a class (and instantiate an object off of it) using one of these syntax:
function dynclass(o):Object
{
var ctor:Function = o.class;
return new ctor();
}
e.g.
levelInfo = [ { name: level1, class: hero.dragoon }, { name: level2, class: hero.zealot } ];
var obj = dynclass(levelInfo[currentlevel].class);
The only caveat to this approach is that all the level info is hardcoded in your code. If you need the flexibility of being able to specify all these in an XML file or from a database feed, if you need a way to instantiate a class based on string.
function dynclass(classname:String)
{
var ctor:Function = eval(classname);
return new ctor();
}
e.g. var obj = dynclass("classpath.myclass");
The second approach is definitely more flexible because it allows you to pass in a string, which means the user can literally type in the class name in a textbox to create something.
The only caveat with the second approach is that you must make sure your swf compiles the class code into it by including a reference of the class somewhere in your timeline, like so:
classpath.myclass;
1 Comments:
If you are alone, call this number 800-211-9293. Connect with Real Singles from your local area instantly for only $0.99/min with a $4.99 connection fee. A true Match is only one phone call away 800-211-9293. Meet people with common interests and desires now. Check it out. 800-211-9293
Post a Comment
Subscribe to Post Comments [Atom]
<< Home