I'm in a situation where I need to check if an object is an instance of a child class but at the same time instanceof
should return false
for the parent class.
I have figured out a way but I'm not able to think of edge cases where this approach might fail. Is this the correct way?
This is the simplified version of the code:
class Employee {
static [Symbol.hasInstance]( instance ) {
return Object.getPrototypeOf( instance ) === this.prototype;
}
}
class Manager extends Employee {
}
class AssistantManager extends Manager {
}
const e1 = new AssistantManager( 'Dean' );
console.log( e1 instanceof Employee ) // false
console.log( e1 instanceof Manager ) // false
console.log( e1 instanceof AssistantManager ) // true