js实现instanceof
instanceof 运算符简介
instanceof 是 JavaScript 中的运算符,用于检测构造函数的 prototype 属性是否出现在对象的原型链中。其语法为 object instanceof constructor,返回布尔值。
手动实现 instanceof
以下是手动实现 instanceof 功能的代码示例:
function myInstanceof(obj, constructor) {
// 检查 constructor 是否有效
if (typeof constructor !== 'function' || !constructor.prototype) {
throw new TypeError('Right-hand side of instanceof is not callable');
}
// 处理原始类型直接返回 false
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是有效的构造函数(具有prototype属性)。 - 原始值处理:原始类型(非对象)直接返回
false,符合原生instanceof的行为。 - 原型链遍历:使用
Object.getPrototypeOf()获取对象的原型,并沿原型链向上查找。 - 匹配判断:如果找到与构造函数
prototype相同的对象,返回true。
使用示例
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(123, Number)); // false(原始类型)
注意事项
- 跨框架对象检测可能失效,不同执行环境的相同构造函数可能不共享原型。
- 手动实现无法完全模拟内置对象(如
Array、Date)的检测行为。 - 现代 JavaScript 中推荐使用
Symbol.hasInstance自定义instanceof行为。
替代方案
对于更可靠的类型检测,可考虑:
Object.prototype.toString.call(obj)Array.isArray()等内置方法typeof运算符(针对原始类型)







