实现instanceof js
实现 JavaScript 的 instanceof 操作符
instanceof 用于检测构造函数的 prototype 属性是否出现在对象的原型链中。以下是手动实现 instanceof 功能的两种方法:

方法一:递归实现
通过递归遍历对象的原型链,检查是否存在目标构造函数的 prototype。

function myInstanceof(obj, constructor) {
if (obj === null || typeof obj !== 'object') return false;
let proto = Object.getPrototypeOf(obj);
if (proto === constructor.prototype) return true;
return myInstanceof(proto, constructor);
}
方法二:循环实现
通过循环遍历原型链,避免递归可能导致的栈溢出问题。
function myInstanceof(obj, constructor) {
if (obj === null || typeof obj !== 'object') return false;
let proto = obj.__proto__;
while (proto) {
if (proto === constructor.prototype) return true;
proto = proto.__proto__;
}
return false;
}
使用示例
function Person() {}
const p = new Person();
console.log(myInstanceof(p, Person)); // true
console.log(myInstanceof(p, Object)); // true
console.log(myInstanceof([], Array)); // true
注意事项
- 仅适用于对象类型(非
null和原始值)。 - 使用
Object.getPrototypeOf()或__proto__均可访问原型链。 - 循环实现更高效,适合深层原型链的场景。






