views:

3153

answers:

3

How do you get an instance of the actionscript class Class from an instance of that class?

In Python, this would be x.__class__; in Java, x.getClass();.

I'm aware that certain terrible hacks exist to do this, but I'm looking for a built-in language facility, or at least a library routine built on something reliable.

+5  A: 

Any reason you couldn't do this?

var s:Sprite = new flash.display.Sprite();

var className:String = flash.utils.getQualifiedClassName( s );
var myClass:Class = flash.utils.getDefinitionByName( className ) as Class;

trace(className ); // flash.display::Sprite
trace(myClass); // [class Sprite]

var s2 = new myClass();
trace(s2); // [object Sprite]

I don't know a way to avoid round-tripping through a String, but it should work well enough.

fenomas
This would work, but the performance for getQualifiedClassName and getDefinitionByName is pretty poor.mike chambers
mikechambers
+23  A: 

You can get it through the 'constructor' property of the base Object class. i.e.:

var myClass:Class = Object(myObj).constructor;
Gerald
That works too :D
fenomas
Wow that actually works! Where did you find that little gem?
Iain
As far as I know it's my own gem, though the Adobe docs for the Object class mentions the constructor property and what it is. I've never seen it used that way anywhere else.
Gerald
That's brilliant. Love this site.
Jason Maskell
Some more discussion here:http://joshblog.net/2009/05/11/retrieve-the-class-used-to-instantiate-an-object-in-as3/One slight alternative would be to do:var classRef:Class = myObj["constructor"] as Class;This also gets around the strict compiler checks. Not sure which one performs better.mike chambers
mikechambers
This does not work on objects that subclass Proxy, such as XML. See this answer - http://stackoverflow.com/questions/468925/in-actionscript3-how-do-you-get-a-reference-to-an-objects-class/472300#472300
Richard Szalay
A: 

Thanks fenomas. This is the exact thing I was looking for.

I have a class 'Child' that extends from 'Parent'. I need to access Child's static properties from the parent.

I passed myClass when I called the super(); method in the 'Child' class.

If there is a better way to do please let me know.

ArunAnjay Anantha
I could answer that but you should create a separate question.
Mims H. Wright