实现instanceof js
实现 instanceof 操作符
JavaScript 中的 instanceof 操作符用于检测构造函数的 prototype 属性是否出现在对象的原型链中。以下是手动实现 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;
}
工作原理
- 获取对象的原型和构造函数的
prototype属性 - 沿着原型链向上查找,比较当前原型是否等于构造函数的
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({}, Array)); // false
注意事项
- 原始值(如
'string',42,true)使用instanceof会始终返回false - 如果构造函数的
prototype被修改,instanceof的结果也会相应变化 - 跨框架对象检测可能不可靠,因为不同执行环境有不同的全局对象
替代方案
对于更可靠的类型检查,可以考虑使用:
Object.prototype.toString.call(obj) === '[object Array]'
或 ES6 引入的:

Array.isArray(obj)






