Home > OS >  AS3: How to strictly test if instance is Object type?
AS3: How to strictly test if instance is Object type?

Time:09-17

How can I test if an instance is of the type Object? If I try the is operator, all Object subclasses return true as well.

var o:Object = {};
var s:Sprite = new Sprite();
trace(o is Object); //true
trace(s is Object); //true

How can I have it only return true of the instance is an Object superclass and not any one of it's myriad of subclasses?

CodePudding user response:

The flash.utils.getQualifiedClassName(...) method returns the exact String representation of the class for both instance and its class passed as the method argument.

import flash.utils.getQualifiedClassName;

var O:Object = {};
var S:Sprite = new Sprite;

var GQ:Function = getQualifiedClassName;

trace(GQ(O) == GQ(Object)); // true
trace(GQ(S) == GQ(Object)); // false

UPD: There's another way to do it, although I personally like it less. You can use the Object.constructor property which probably points to the class constructor of the given instance.

function isObject(target:Object):Boolean
{
    return target.constructor == Object
}

trace(isObject(O)); // true
trace(isObject(S)); // false
  • Related