I would like to check if object has a DisplayObject as one of it's ancestors and perform some operations on it if it has. Any quick and easy way to do this?
2 Answers
If by "ancestor" you mean "one of superclasses", then the solution is simple: in ActionScript an object can have "a DisplayObject as one of it's ancestors" only if object's class has DisplayObject in it's inheritance chain, which is easily checked by casting. Inheritance creates "IS A" relation between parent and child classes, so a child's instance IS An instance of parent (and of any other distant ancestor).
var object:* = ....;
if (object is DisplayObject) {
var displayObject:DisplayObject = object as DisplayObject;
// object has DisplayObject class in it's inheritance chain
// do something with object using displayObject reference
}
or
var object:* = ....;
var displayObject:DisplayObject = object as DisplayObject;
if (displayObject != null) {
// object has DisplayObject class in it's inheritance chain
// do something with object using displayObject reference
}

- 3,522
- 17
- 32
-
Loving the simpler solution. +1 – shanethehat Jul 03 '11 at 11:51
complete rewrite due to misunderstanding the question
Edit A faster way than my first suggestion is to use a combination of flash.utils.getQualifiedClassName
and flash.utils.getQualifiedSuperclassName
as suggested in the documentation to check for superclass of each ancestor class. Here's a simple function that will do that for you:
function containsAncestor($obj:*,$className:String):Boolean {
var qn:String = getQualifiedClassName($obj);
while(qn != "Object") {
if(qn == $className) return true;
qn = getQualifiedSuperclassName(getDefinitionByName(qn));
}
return false;
}
//////////////////////////////////
//usage example:
//////////////////////////////////
var mc:MovieClip = new MovieClip();
trace(containsAncestor(mc,"flash.display::DisplayObject")); //true
trace(containsAncestor(mc,"flash.display::BitmapData")); //false
What you need is the describeType function from flash.utils. This produces an XML representation of the object, including the full list of ancestor classes back to Object. The beginning of the output for MovieClip looks like this:
<type name="flash.display::MovieClip" base="flash.display::Sprite" isDynamic="true" isFinal="false" isStatic="false">
<extendsClass type="flash.display::Sprite"/>
<extendsClass type="flash.display::DisplayObjectContainer"/>
<extendsClass type="flash.display::InteractiveObject"/>
<extendsClass type="flash.display::DisplayObject"/>
<extendsClass type="flash.events::EventDispatcher"/>
<extendsClass type="Object"/>
So all that remains for you to do is loop though the extendsClass nodes and check for the presence of DisplayObject
.

- 15,460
- 11
- 57
- 87