1

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 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

After a quick check, your current provided solution fails to identify instance of itself, which is do require just as new Type instanceof Type can identify self type
@Werlious Yes, you can handle that as a special case. That was only an example.
Ah ok, I see your edit. I appreciate it
0

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

1 Comment

I'm wary of this, I know a prototype chain should never get that long, but I avoid recursion at all costs

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.