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



Question:

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


Solution:1

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;  


Solution:2

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.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »