AS3: How to implement instanceOf with classes?

2019-09-05 15: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.