JavaScript check if object is an instance of current class

Viewed 151

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
1 Answers

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

Related