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