js instanceof实现
instanceof 的实现原理
instanceof 运算符用于检测构造函数的 prototype 属性是否出现在对象的原型链上。其核心逻辑是通过递归遍历对象的原型链,与构造函数的 prototype 属性进行比较。
手动实现 instanceof
以下是一个手动实现 instanceof 功能的代码示例:
function myInstanceof(obj, constructor) {
// 获取对象的原型
let proto = Object.getPrototypeOf(obj);
// 获取构造函数的原型
const prototype = constructor.prototype;
// 遍历原型链
while (proto !== null) {
if (proto === prototype) {
return true;
}
proto = Object.getPrototypeOf(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
console.log(myInstanceof([], Object)); // true
console.log(myInstanceof([], Function)); // false
实现要点
- 使用
Object.getPrototypeOf获取对象的原型 - 通过循环不断向上查找原型链
- 每次比较当前原型是否等于构造函数的
prototype属性 - 如果找到匹配则返回
true,如果原型链尽头(null)仍未找到则返回false
注意事项
- 原始类型(如数字、字符串等)使用
instanceof会始终返回false - 如果右侧不是可调用的构造函数(如普通对象),会抛出 TypeError
- 跨框架对象检测可能会有问题,因为不同框架有各自的全局环境







