Q21: Implement Custom myInstanceOf Operator
Replicate the behavior of the instanceof operator by traversing the prototype chain of an object to check for matching constructor prototypes.
Custom instanceof Implementation
function myInstanceOf(obj, constructor) {
if (obj === null || typeof obj !== 'object' && typeof obj !== 'function') {
return false;
}
let proto = Object.getPrototypeOf(obj);
const targetProto = constructor.prototype;
while (proto !== null) {
if (proto === targetProto) return true;
proto = Object.getPrototypeOf(proto);
}
return false;
}
console.log(myInstanceOf([], Array)); // true
console.log(myInstanceOf([], Object)); // true💡 Walks Object.getPrototypeOf(obj) upward until finding constructor.prototype or reaching the null prototype root.
Key Takeaways
- Traverses Object.getPrototypeOf(obj) upward step by step.
- Returns true if target constructor.prototype is found anywhere along the prototype chain.
Knowledge Check
What value does Object.getPrototypeOf() return when called at the top termination point of the prototype chain?