JavaScriptFundamental (ES6), part 2
Customize instanceof with Symbol.hasInstance in JavaScript
67 Symbol.hasInstance rewrites instanceof
hardx instanceof C asks C whether it recognises x. Give a plain object a Symbol.hasInstance method and use it on the right of instanceof. Then duck-type a class with a static one, make it disagree with the prototype chain in both directions, and confirm what instanceof does with a right-hand side that has neither.
Stuck? Three hints, smallest first
- 1. The method receives the left operand and returns something truthy or falsy. It is coerced to a boolean.
- 2. On a class, write it as
static [Symbol.hasInstance](value). - 3. Without the symbol, the right-hand side must be callable, or
instanceofthrows.
const attemptName = (fn) => { try { fn(); return 'no error'; } catch (err) { return err.name; } };
// Not a function, not a constructor, still usable on the right of instanceof.
const Callable = { [Symbol.hasInstance]: (v) => typeof v === 'function' };
const notCallable = {};
const functionMatches = [(() => {}) instanceof Callable, 42 instanceof Callable];
const withoutTheSymbol = attemptName(() => 42 instanceof notCallable);
const rightSideType = typeof Callable;
class Payable {
static [Symbol.hasInstance](value) {
return Boolean(value) && typeof value.amount === 'number' && typeof value.pay === 'function';
}
constructor(amount) { this.amount = amount; }
pay() { return 'paid ' + this.amount; }
}
const duck = { amount: 45000, pay: () => 'transfer sent' };
const duckPasses = duck instanceof Payable;
const notInTheChain = [Object.getPrototypeOf(duck) === Payable.prototype, Payable.prototype.isPrototypeOf(duck)];
const real = new Payable(45000);
const realPasses = real instanceof Payable;
const halfShaped = { amount: 45000 } instanceof Payable;
// It can refuse a genuine instance just as easily.
class Fussy {
static [Symbol.hasInstance]() { return false; }
}
const genuine = new Fussy();
const refused = [genuine instanceof Fussy, Object.getPrototypeOf(genuine) === Fussy.prototype];
// What normally runs is Function.prototype[Symbol.hasInstance], and it is callable.
const theDefault = Function.prototype[Symbol.hasInstance];
const defaultAnswers = [theDefault.call(Array, []), theDefault.call(Array, 'Lagos')];
const primitiveArrives = [] instanceof Callable;
console.log('function instanceof Callable:', functionMatches);
console.log('duck typed :', duckPasses, '| in the chain:', notInTheChain);
console.log('genuine instance refused :', refused);
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('a plain object with hasInstance works on the right of instanceof', functionMatches, [true, false]);
test('even though it is not a function and has no prototype property', [rightSideType, 'prototype' in Callable], ['object', false]);
test('without the symbol, a non-callable right-hand side is a TypeError', withoutTheSymbol, 'TypeError');
test('a static hasInstance duck-types: the right shape passes', [duckPasses, halfShaped], [true, false]);
test('and it passes without being anywhere in the prototype chain', notInTheChain, [false, false]);
test('a genuine instance passes too, because it happens to fit the same shape', realPasses, true);
test('but the trap can refuse a genuine instance while the chain still holds', refused, [false, true]);
test('the default behaviour is itself a callable method you can invoke directly', defaultAnswers, [true, false]);
test('and the check receives the left operand whatever it is, primitives included', [primitiveArrives, 'Lagos' instanceof Callable], [false, false]);
instanceof is not a language primitive that walks prototypes. It is a dispatch: look up Symbol.hasInstance on the right operand, call it with the left one, coerce the answer to a boolean. Only when the symbol is absent does the fallback — Function.prototype[Symbol.hasInstance], which does walk the chain — run. The eighth assertion calls that fallback by hand, which is the clearest way to see it is just a method.
The seventh assertion is the warning. genuine instanceof Fussy is false while Object.getPrototypeOf(genuine) === Fussy.prototype is true. instanceof and the prototype chain are now two different questions, and any code that assumed they were the same — a type guard, a serialiser, a dependency-injection container — is wrong about this class and has no way of knowing.
Where it earns its place: a branded check that survives module duplication. Two copies of a library in one bundle give two distinct classes, so a real instance from copy A fails instanceof against copy B; a hasInstance that tests for a symbol-keyed brand instead passes. Also for abstract shapes — "anything payable" — where there is no single base class to inherit from.
Where it does not: as a validator. The fourth assertion shows the shape check accepting a plain object literal, which is the intent here, but shape checks drift from the class they claim to describe. Add a required field to Payable and the duck still passes.