Sub topic 11
Customizing instanceof with Symbol.hasInstance
This chapter assumes you know how ES6 classes and static methods work, how prototype chains connect objects, and how computed property names like [Symbol.iterator] define symbol-keyed methods. It covers the hook that lets an object decide what x instanceof Y returns.
How instanceof Actually Works
When JavaScript evaluates value instanceof Target, it does not walk the prototype chain right away. It first looks up Target[Symbol.hasInstance]. If that method exists, the engine calls it with value and converts the result to a boolean. Only if the method is missing does it fall back to the plain prototype-chain check.
Every function inherits a default Symbol.hasInstance from Function.prototype. That default walks the prototype chain. So for ordinary classes you get the familiar behavior without doing anything.
const defaultCheck = Function.prototype[Symbol.hasInstance];
console.log(defaultCheck.call(Array, [])); // true
console.log(defaultCheck.call(Array, {})); // false
console.log([] instanceof Array); // true (same check)Overriding the Check in a Class
To customize the check, define a static method under Symbol.hasInstance. It is static because instanceof reads it from the right-hand operand, which is the class itself and not an instance.
class Even {
static [Symbol.hasInstance](value) {
return Number.isInteger(value) && value % 2 === 0;
}
}
console.log(2 instanceof Even); // true
console.log(3 instanceof Even); // falseThe default check always returns false for primitives. A custom method can return true for them, as 2 instanceof Even shows.
The Right Side Does Not Need to Be a Function
Because the hook is looked up before anything else, any object that has the method works on the right side of instanceof. You can use this for duck-typing checks:
const Iterable = {
[Symbol.hasInstance](value) {
return value != null && typeof value[Symbol.iterator] === 'function';
}
};
console.log([1, 2] instanceof Iterable); // true
console.log('abc' instanceof Iterable); // true
console.log(new Map() instanceof Iterable); // true
console.log(42 instanceof Iterable); // falseCommon Errors
Assigning the Hook to a Plain Function
Function.prototype[Symbol.hasInstance] is non-writable. Plain assignment to a function therefore fails: it throws a TypeError in strict mode and does nothing in sloppy mode. Use Object.defineProperty instead. The static class syntax works because class definitions create the property directly instead of assigning it.
'use strict';
function Positive() {}
try {
Positive[Symbol.hasInstance] = (v) => v > 0;
} catch (e) {
console.log(e instanceof TypeError); // true
}
Object.defineProperty(Positive, Symbol.hasInstance, {
value: (v) => typeof v === 'number' && v > 0
});
console.log(5 instanceof Positive); // true
console.log(-1 instanceof Positive); // falseSubclasses Inherit the Override
Static methods are inherited. If class Big extends Even {} exists, then 4 instanceof Big uses Even's logic and returns true. If a subclass needs different behavior, it has to override the method itself.
Breaking What Callers Expect
| Situation | Default behavior | With Symbol.hasInstance |
|---|---|---|
| Primitive on the left | Always `false` | Whatever the method returns |
| Non-function on the right | `TypeError` | Works if the method exists |
| Object from another realm (iframe) | Often `false` | Can check structure instead |
Exercise
You write function Shape() {} in a strict-mode module, then Shape[Symbol.hasInstance] = (v) => 'area' in Object(v);. What happens, and how do you fix it?
Show answer
The assignment throws a TypeError because Shape inherits a non-writable Symbol.hasInstance from Function.prototype, and strict mode makes the failed write throw. Fix it with Object.defineProperty(Shape, Symbol.hasInstance, { value: (v) => 'area' in Object(v) }), or declare Shape as a class with a static [Symbol.hasInstance] method.
Exercise
Given class Even with the static hasInstance shown above and class Big extends Even {}, what does 6 instanceof Big print, and why?
Show answer
It prints true. Big inherits Even's static Symbol.hasInstance method through its constructor prototype chain, so instanceof calls Even's integer-and-even check rather than the default prototype walk.