Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In ActionScript3, how do you get a reference to an object's class?

In ActionScript3, how do you get a reference to an object's class?

like image 836
Iain Avatar asked Jan 22 '09 12:01

Iain


2 Answers

It's worth noting that the XML objects (XML, XMLList) are an exception to this (ie. (new XML() as Object).constructor as Class == null). I recommend falling back to getDefinitionByName(getQualifiedClassName) when constructor does not resolve:

function getClass(obj : Object) : Class
{
    var cls : Class = (obj as Class) || (obj.constructor as Class);

    if (cls == null)
    {
        cls = getDefinitionByName(getQualifiedClassName(obj));
    }

    return cls;
}

Note that getDefinitionByName will throw an error if the class is defined in a different (including a child) application domain from the calling code.

like image 161
Richard Szalay Avatar answered Sep 20 '22 12:09

Richard Szalay


You can use the constructor property if your object has been created from a class (from the docs: "If an object is an instance of a class, the constructor property holds a reference to the class object. If an object is created with a constructor function, the constructor property holds a reference to the constructor function."):

var classRef:Class = myObject.constructor as Class;

Or you can use flash.utils.getQualifiedClassName() and flash.utils.getDefinitionByName() (not a very nice way since this entails unnecessary string manipulation in the implementations of these library functions):

var classRef:Class = getDefinitionByName(getQualifiedClassName(myObject)) as Class;
like image 39
hasseg Avatar answered Sep 18 '22 12:09

hasseg