js实现intanceof
js实现instanceof
在JavaScript中,instanceof运算符用于检测构造函数的prototype属性是否出现在对象的原型链上。以下是手动实现instanceof功能的代码示例:

function myInstanceof(obj, constructor) {
let proto = Object.getPrototypeOf(obj);
while (proto !== null) {
if (proto === constructor.prototype) {
return true;
}
proto = Object.getPrototypeOf(proto);
}
return false;
}
实现原理
- 获取对象的原型链:使用
Object.getPrototypeOf(obj)获取对象的原型。 - 遍历原型链:通过循环不断向上查找原型链。
- 比较原型:检查当前原型是否等于构造函数的
prototype属性。 - 返回结果:如果找到匹配的原型则返回
true,否则遍历完整个原型链后返回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({}, Array)); // false
注意事项
- 原始类型检测:
instanceof对原始类型(如number、string、boolean)无效,手动实现也需注意这一点。 - 跨框架对象:不同iframe或window环境下的对象可能无法正确检测。
Symbol.hasInstance:ES6允许构造函数自定义instanceof行为,手动实现未考虑此特性。
该实现模拟了原生instanceof的核心功能,适用于大多数常规场景。






