2

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
Siddharth Thevaril
  • 3,722
  • 3
  • 35
  • 71
  • 6
    This is a terrible idea: changing how `instanceof` works will confuse every single person who ever deals with this code, including you once you've forgotten why you thought that was a good idea. If you want to know what *specific* class something is, check the constructor name. – Jared Smith Oct 18 '20 at 20:18
  • 5
    Isn't it better to check the constructor name instead of changing the `instanceof` definition? `instanceof` is a widely used keyword and could seriously affect the maintainability of the code. – Kalesh Kaladharan Oct 18 '20 at 20:18

1 Answers1

0

I found this code of someone trying to accomplish the same. It recommends checking the constructor. Might be helpful.

He mentions to check the constructor, like following:

if (!value || value.constructor !== Foo)
  throw 'InvalidArgumentException: (...)';

Or the prototype of the object (this is more similar to what instanceof does):

if (!value || Object.getPrototypeOf(value) !== Foo.prototype)
  throw 'InvalidArgumentException: (...)';

Check if object is a 'direct instance' of a class

Tom
  • 387
  • 2
  • 12
  • Please don't just link another question (which might get deleted), put the actual content itself in your answer as well. – Bergi Oct 18 '20 at 20:48