Using ES6 class
syntax, I'm wondering why the instanceof
operator doesn't work for the inheritance chain when there are more than one chain of inheritance?
(optional read)How
instanceof
operator works?In
obj instanceof Constructor
, theinstanceof
operator checks if the'prototype'
property of theConstructor
function is present in the prototype chain of theobj
. If it is present, returntrue
. Otherwise,false
.
In the following snippet, the BTError
inherits from Error
(1.) and SomeError
extends from BTError
(3.).
But as we can see from (4.), the instanceof
operator results false
for new SomeError() instanceof BTError
which in my understanding should be 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
Is there anything non-trivial which I'm unable to comprehend or is instanceof
operator just acting weird?