Showing posts with label reflection. Show all posts
Showing posts with label reflection. Show all posts

Friday, January 25, 2008

Cute EcmaScript

The following is a nifty trick that works in JavaScript, but you should be able to tweak it slightly to work in ActionScript as it leverages EcmaScript features.


function Train(){
this.name = "Choo Choo";
this.show = function(){
return this.name;
};
};
var engine = new Train;
engine.name = "Orient Express";
function go(){
alert(engine["show"].call(engine));
}


What is cool is that you can access a function just like any other property of the object. So the go function could take a parameter that would be the name of the function to call on the engine object. It's like reflection, only better.

Wednesday, December 12, 2007

ActionScript Reflection Workarounds

ActionScript has some nice reflection features. However, if you are used to Java or C# (for example) then ActionScript can seem kind of sub-par. One of the easiest things to do in Java is to create a new instance of a class dynamically:

Class<MyAwesomeClass> clazz = MyAwesomeClass.class;
MyAwesomeClass instance = clazz.newInstance();

Clearly this assumes a default constructor, but you get the picture. The equivalent in AS is:

var x:MyGreatClass;
var clazz:Class = flash.utils.getDefinitionByName("MyGreatClass") as Class;
var instance:MyGreatClass = new clazz() as MyGreatClass;
A couple of things to notice here. First, you have to declare a variable of the given type. Otherwise the AVM2 virtual machine is not smart enough to load the class and will blow up on the second line (thanks Wikipedia!) Next the standard AS Function getDefinitionByName returns an Object, not a Class, so you have to cast it. The only nice part is that you get to use the new operator with the instance variable clazz. Ah, finally we get a job-of-dynamic-language moment. To improve on this, I add a boilerplate method to my classes:

public static get clazz():Class
{
return MyGreatClass;
}

This let's me do the following:

var clazz:Class = MyGreatClass.clazz;
var instance:MyGreatClass = new clazz() as MyGreatClass;

Not quite as nice Java still, but close! The first line causes MyGreatClass to get loaded by the VM while at the same time providing a handle on the Class in question in a very convenient manner.