Implement the instanceof Operator
Implement myInstanceOf(obj, Constructor) — a reimplementation of the instanceof operator.
instanceof walks obj's prototype chain looking for Constructor.prototype. If found at any level, return true.
dog.__proto__ → Dog.prototype
→ Animal.prototype
→ Object.prototype
→ null
myInstanceOf(dog, Dog); // true (Dog.prototype found at level 1)
myInstanceOf(dog, Animal); // true (Animal.prototype found at level 2)
myInstanceOf(dog, Cat); // false (Cat.prototype never found)
Examples
Input: "direct"
Output: true
Input: "inherited"
Output: true
Hints
Start with `let proto = Object.getPrototypeOf(obj)` — this gives you the first link in the chain.
Loop: if `proto === Constructor.prototype` return true. If `proto === null` return false. Otherwise `proto = Object.getPrototypeOf(proto)`.
Primitives (numbers, strings) have no prototype chain — `Object.getPrototypeOf(42)` returns `Number.prototype`, not null, so handle the non-object case first.
Related Problems
Implement the instanceof Operator
Implement myInstanceOf(obj, Constructor) that walks the prototype chain to check if Constructor.prototype appears anywhere in obj's chain.