My curiosity lies in understanding why the instanceof
operator fails to work properly for the inheritance chain when there are multiple chains of inheritance involved.
(optional read)How does the
instanceof
operator function?When using
obj instanceof Constructor
, theinstanceof
operator essentially checks if the'prototype'
property of theConstructor
function is found within the prototype chain of theobj
. If it is found, true is returned; otherwise, false is returned.
In the code snippet below, we observe that BTError
inherits from Error
(1.) while SomeError
extends from BTError
(3.).
However, it appears that despite expectations (4.), the instanceof
operation results in false
for
new SomeError() instanceof BTError
, which should ideally return true
.
class BTError extends Error {}
console.log('1.', Reflect.getPrototypeOf(BTError.prototype) === Error.prototype); // 1. true
console.log('2.', new BTError() instanceof Error); // 2. true
console.log('');
class SomeError extends BTError {}
console.log('3.', Reflect.getPrototypeOf(SomeError.prototype) === BTError.prototype); // 3. true
console.log('4.', new SomeError() instanceof BTError); // 4. false
console.log('');
class SpecificError extends SomeError {}
console.log('5.', Reflect.getPrototypeOf(SpecificError.prototype) === SomeError.prototype); // 5. true
console.log('6.', new SpecificError() instanceof Error); // 6. true
console.log('7.', new SpecificError() instanceof BTError); // 7. false
console.log('8.', new SpecificError() instanceof SomeError); // 8. false
Question
Am I missing something significant here or is the behavior of the instanceof
operator simply peculiar?