function customInstanceof(obj, constructor) {
// 检查传入的对象是否为对象类型
if (typeof obj !== 'object' || obj === null) {
return false;
}
// 获取传入构造函数的原型
let proto = Object.getPrototypeOf(obj);
// 循环查找原型链,直到找到构造函数的原型,或者到达原型链的末尾(null)
while (proto !== null) {
if (proto === constructor.prototype) {
return true;
}
proto = Object.getPrototypeOf(proto);
}
return false;
}
// 示例用法
function Person(name) {
this.name = name;
}
const person = new Person('Alice');
console.log(customInstanceof(person, Person)); // true
console.log(customInstanceof(person, Object)); // true,因为所有对象都是 Object 的实例
console.log(customInstanceof(person, Array)); // false
console