Search code examples
javascriptnode.jsinstanceofprototypal-inheritance

Is there a static version of `instanceof`?


Is there a static equivalent of instanceof? I.E., rather than: obj1 instanceof Type something like: TypeA instanceof TypeB?

I couldn't find anything on the matter, so I hacked together this:

function InstanceOf(type,parent) {
    do{ if(type === parent) return true;}
    while(type = Object.getPrototypeOf(type));
    return false;
}
//...
Instanceof(ChildClass, ParentClass); // = boolean

But I feel like there's a better/more native way to do this, but again, can't find anything on it.

Is there a better/standard way do check static class inheritance? Or is my hack about the best it's gonna get?

Update So, I got curious and ran a perf test on both the version I hacked and the one provided by the accepted answer, and the getPrototypeOf version is about twice as fast when ran 100,000 times. Also, no, I can't post the test code, I did it in the node REPL


Solution

  • You can use isPrototypeOf.

    class A {}
    class B extends A {}
    class C extends B {}
    const InstanceOf = (type, parent) => type === parent || parent.prototype.isPrototypeOf(type.prototype);
    console.log(InstanceOf(B, A));
    console.log(InstanceOf(A, A));
    console.log(InstanceOf(C, A));
    console.log(InstanceOf(C, B));
    console.log(InstanceOf(B, C));