js实现myinstanceof


实现 myInstanceOf 方法
在 JavaScript 中,instanceof 运算符用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上。以下是手动实现 myInstanceOf 的方法:
function myInstanceOf(obj, constructor) {
if (typeof constructor !== 'function') {
throw new TypeError('Right-hand side of instanceof is not callable');
}
if (obj === null || typeof obj !== 'object') {
return false;
}
let proto = Object.getPrototypeOf(obj);
while (proto !== null) {
if (proto === constructor.prototype) {
return true;
}
proto = Object.getPrototypeOf(proto);
}
return false;
}
代码解析
- 检查
constructor是否为函数,如果不是则抛出类型错误。 - 检查
obj是否为对象或不为null,如果不是则直接返回false。 - 获取
obj的原型对象,并沿着原型链向上查找。 - 如果找到与
constructor.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(123, Number)); // false
注意事项
- 该方法模拟了原生
instanceof的行为,但原生instanceof对基本类型(如Number、String)的处理略有不同。 - 如果传入的
obj是基本类型(非对象),直接返回false,与原生instanceof行为一致。






