Is there a static version of `instanceof`?

79 views Asked by At

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

2

There are 2 answers

3
Unmitigated On BEST ANSWER

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));

1
Kolzar On

In JavaScript, the instanceof operator is used for checking if an object is an instance of a particular class or constructor. However, for checking the inheritance relationship between two constructor functions (class-like structures), there isn't a direct built-in equivalent.

Your solution using a custom function is a reasonable approach for checking static class inheritance. However, you can also use the Object.getPrototypeOf method in a simpler way:

function isStaticInstanceOf(child, parent) {
    return child === parent || (!!child && isStaticInstanceOf(Object.getPrototypeOf(child), parent));
}

class Animal {}
class Dog extends Animal {}
class Rottweiler extends Dog {}


console.log(isStaticInstanceOf(Dog, Animal)); // true
console.log(isStaticInstanceOf(Dog, Dog)); // true
console.log(isStaticInstanceOf(Rottweiler, Animal)); // true
console.log(isStaticInstanceOf(Rottweiler, Dog)); // true
console.log(isStaticInstanceOf(Dog, Object)); // false
console.log(isStaticInstanceOf(Dog, Function)); // false