describeType()
在计算上是非常慢的。如果您需要确定未经证实的类的继承链,请考虑使用Class.prototype
和prototype.isPrototypeOf()
。这允许您检查继承和相等性,如果您拥有的只是Classes本身(而不是作为该Class实例的对象)。
如果您只有类名称的字符串表示形式(与类本身相反),则必须先将其转换为适当的类,并使用flash.utils.getDefinitionByName()
,假设您至少在代码中声明了该类。如果该类仅存在于加载的SWF库中的某处,则可能必须使用类似ApplicationDomain.currentDomain.getDefinitionByName()
或contextLoader.currentDomain.getDefinitionByName()
之类的内容。
下面是一个工作示例,它接受Classes或String类名,并检查第一个是否在第二个继承链中。额外的参数允许您决定如果两个类是相同的而不是第一个扩展第二个类,那么是否要返回false。
/**
* Determines whether the childClass is in the inheritance chain of the parentClass. Both classes must be declared
* within the current ApplicationDomain for this to work.
*
* @param childClass
* @param parentClass
* @param mustBeChild
*/
public static function inheritsFrom(childClass:*, parentClass:*, mustBeChild:Boolean = false) {
var child:Class,
parent:Class;
if (childClass is Class) {
child = childClass;
} else if (childClass is String){
child = getDefinitionByName(childClass) as Class;
}
if (! child) {
throw new ArgumentError("childClass must be a valid class name or a Class");
}
if (parentClass is Class) {
parent = parentClass;
} else if (parentClass is String){
parent = getDefinitionByName(parentClass) as Class;
}
if (! parent) {
throw new ArgumentError("parentClass must be a valid class name or a Class");
}
if (parent.prototype.isPrototypeOf(child.prototype)) {
return true;
} else {
if (mustBeChild) {
return false;
} else {
if (parent.prototype === child.prototype) {
return true;
}
}
}
return false;
}
太好了,谢谢。来自丰富的Java 6 API,我发现自己必须随时使用Flash/Flex,grrr ;-)重新发明轮子。 – jmdecombe 2009-11-10 15:38:24
这很好,但相对较慢。如果你偶尔会这样做,那就没问题。否则,请考虑'isPrototypeOf()'。 – 2014-08-13 16:58:34