js instanceof实现
实现 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;
}
使用示例
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
实现原理说明
手动实现 instanceof 的关键在于遍历对象的原型链。通过 Object.getPrototypeOf 获取对象的原型,并与构造函数的 prototype 属性比较。如果找到匹配的原型,返回 true;如果遍历到原型链顶端(null)仍未找到匹配,返回 false。
边界情况处理
- 如果
obj不是对象(如基本类型null、undefined、number等),直接返回false。 - 如果
constructor不是函数(如基本类型或非构造函数对象),抛出TypeError。
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);
const prototype = constructor.prototype;
while (proto !== null) {
if (proto === prototype) {
return true;
}
proto = Object.getPrototypeOf(proto);
}
return false;
}
与原生 instanceof 的差异
原生 instanceof 还支持检查 Symbol.hasInstance 方法(如果构造函数定义了该方法)。手动实现通常不包含这一特性,但可以通过以下方式扩展:

function myInstanceof(obj, constructor) {
if (typeof constructor !== 'function') {
throw new TypeError('Right-hand side of instanceof is not callable');
}
if (typeof constructor[Symbol.hasInstance] === 'function') {
return constructor[Symbol.hasInstance](obj);
}
if (obj === null || typeof obj !== 'object') {
return false;
}
let proto = Object.getPrototypeOf(obj);
const prototype = constructor.prototype;
while (proto !== null) {
if (proto === prototype) {
return true;
}
proto = Object.getPrototypeOf(proto);
}
return false;
}






