6

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

ThinkingStiff
  • 64,767
  • 30
  • 146
  • 239
Iain
  • 9,432
  • 11
  • 47
  • 64
  • 1
    Dupe: http://stackoverflow.com/questions/203969/how-do-i-get-from-an-instance-of-a-class-to-a-class-object-in-actionscript-3 – bzlm Feb 22 '09 at 11:01

2 Answers2

10

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.

Richard Szalay
  • 83,269
  • 19
  • 178
  • 237
5

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;
hasseg
  • 6,787
  • 37
  • 41