views:

3086

answers:

7

I want to do this in Actionscript:

typeof(control1) != typeof(control2)

to test if two objects are of the same type. This would work just fine in C#, but in Actionscript it doesnt. In fact it returns 'object' for both typeof() expressions because thats the way Actionscript works.

I couldn't seem to find an alternative by looking in the debugger, or on pages that describe typeof() in Actionscript.

Is there a way to get the actual runtime type?

+3  A: 

You'll want to use the Object.prototype.constructor.

From the documentation:

 dynamic class A {}
  trace(A.prototype.constructor);      // [class A]
  trace(A.prototype.constructor == A); // true
  var myA:A = new A();
  trace(myA.constructor == A);         // true

(Conveniently, this is also how to check types in javascript, which is what originally led me to this in the docs)

So, to test this out before I posted here, I tried it in an app I have, in a class called Player. Since the prototype property is static, you can't call it using "this" but you can just skip the scope identifier and it works:

public function checkType():void {
    trace(prototype.constructor, prototype.constructor == Player);
    // shows [class Player] true
}
enobrev
+5  A: 

The best way is to use flash.utils.getQualifiedClassName(). Additionally, you can use flash.utils.describeType() to get an XML document the describes more about the class.

Marcus

A: 

If you want to account for inheritance, then you might want to try something like this:

if (objectA is objectB.constructor || objectB is objectA.constructor)
{
    // ObjectA inherits from ObjectB or vice versa
}
Richard Szalay
A: 

Actionscript 3 has an is operator which can be used to compare objects. Consider the following code:

var mySprite:Sprite = new Sprite();
var myMovie:MovieClip = new MovieClip();

trace(mySprite is Sprite);
trace(myMovie is MovieClip);
trace(mySprite is MovieClip);
trace(myMovie is Sprite);

Which will produce the following output:

true
true
false
false

This will work for built-in classes, and classes you create yourself. The actionscript 2 equivalent of the is operator is instanceof.

A: 

Object obj = new Object(); Object o = new Object();

if(o.getClass().getName().endsWith(obj.getClass().getName())){ return true; }else{ return false; }

A: 

More generally, if you want to test whether objectA is a subtype of objectB

import flash.utils.getDefinitionByName;
import flash.utils.getQualifiedClassName;

...

if (objectA is getDefinitionByName(getQualifiedClassName(objectB)))
{
    ...
}
verveguy