Skip to content

Latest commit

 

History

History
22 lines (18 loc) · 643 Bytes

override-the-behavior-of-instanceof.mdx

File metadata and controls

22 lines (18 loc) · 643 Bytes
category created tags title
Trick
2021-02-23
JavaScript
Override the behavior of instanceof

instanceof doesn't work for primitive types.

If you want to use instanceof all the time, then you can override the behavior of instanceof by implementing a static method with the key of Symbol.hasInstance. In the following code, we create a class called PrimitiveNumber that checks if a value is a number:

class PrimitiveNumber {
    static [Symbol.hasInstance](value) {
        return typeof value === 'number';
    }
}

12345 instanceof PrimitiveNumber; // true
'helloworld' instanceof PrimitiveNumber; // false