instanceof
JS Functions
Medium
15 min
prototypes
objects
symbols
Implement myInstanceOf(value, target), which returns the same result as value instanceof target without using the instanceof operator.
class Animal {}
class Dog extends Animal {}
const rex = new Dog();
myInstanceOf(rex, Dog); // true
myInstanceOf(rex, Animal); // true
myInstanceOf(rex, Object); // true
myInstanceOf(rex, Array); // false
myInstanceOf(42, Number); // false (primitives are never instances)
myInstanceOf(Object.create(null), Object); // false
myInstanceOf(rex, {}); // throws TypeError
Requirements
- If
targetis not an object, throw aTypeError. (Note that functions are objects.) - If
targethas a customSymbol.hasInstancemethod (one that is not the default inherited fromFunction.prototype), call it withvalueand return its result converted to a boolean. - Otherwise, if
targetis not callable, throw aTypeError. - Primitives (
null,undefined, numbers, strings, …) returnfalse. - Otherwise read
target.prototype. If it's not an object, throw aTypeError. - Walk
value's prototype chain withObject.getPrototypeOfand returntrueif you reachtarget.prototype, orfalseif you reachnull.
Follow-up
- Why can
instanceofgive the "wrong" answer for arrays coming from an iframe? What should you use instead? - How does
instanceofbehave with bound functions?
Spotted a mistake or a rights concern? Report an issue