AS3: How to implement instanceOf with classes?

∥☆過路亽.° 提交于 2019-12-14 03:18:13

问题


I want to implement this method

function isInstance(a:Class, b:Class):Boolean;

This is how AS3 work with Classes. Note that MovieClip extends Sprite.

trace(MovieClip is Sprite); // false
trace(Sprite is MovieClip); // false
trace(Sprite is Sprite); // false
trace(Sprite is Object); // true

I been trying the next code but it is not working:

/**
* return if instance of class 'a' can be cast to instant of class 'b'
*/
private function isInstance(a:Class, b:Class):Boolean{
    var superclass:Class = a;
    do {
        if (superclass == b) {
            return true;
        }
        superclass = getSuperClass(a);
    } while (superclass != null);

    return false;
}

private function getSuperClass(claz:Class):Class{
    var qualifiedSuperclassName:String = getQualifiedSuperclassName(claz);
    var returnValue:Class = getDefinitionByName(qualifiedSuperclassName) as Class;
    return returnValue;
}

回答1:


From the ActionScript docs

The is operator should be used instead of the instanceof operator for manual type checking, because the expression x instanceof y merely checks the prototype chain of x for the existence of y (and in ActionScript 3.0, the prototype chain does not provide a complete picture of the inheritance hierarchy).

And their samples:

var mySprite:Sprite = new Sprite(); 
trace(mySprite is Sprite); // true 
trace(mySprite is DisplayObject);// true 
trace(mySprite is IEventDispatcher); // true

It sounds to me like you're trying to do this the hard way.




回答2:


Found solution in this site.

It is simple as that:

private function isSubclassOfSkyboy(a:Class, b:Class): Boolean
{
    if (int(!a) | int(!b)) return false;
    return (a == b || a.prototype instanceof b);
}

There is a use here of instanceof that been deprecated from as3. As I understood he cannot be replaced with is in this case, but correct me if I am wrong. Any way read the article before commenting.



来源:https://stackoverflow.com/questions/20816588/as3-how-to-implement-instanceof-with-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!