I have a situation where I need to check if a constructor (X) has another constructor (Y) in its prototype chain (or is Y itself).
The quickest means to do this might be (new X()) instanceof Y
. That isn't an option in this case because the constructors in question may throw if instantiated without valid arguments.
The next approach I've considered is this:
const doesInherit = (A, B) => {
while (A) {
if (A === B) return true;
A = Object.getPrototypeOf(A);
}
return false;
}
That works, but I can't shake the sense that I'm missing some more straightforward way to check this. Is there one?
Because of the way
instanceof
works, you should be able to doBut this would only test inheritance, you should have to compare
A === B
to test for self-reference:Babel example:
instanceof
is basically implemented as follows:It iterates over the prototype chain of the object and checks whether any of the prototypes equals the constructors
prototype
property.So almost like what you were doing, but internally.