如果一个实例的原型链中出现过相应的构造函数,则返回true
获取实例对象的原型对象:obj.__proto__
获取构造函数的原型对象:Person.prototype
他们都指向构造函数
1.使用递归实现
const myInstanceiof1 = (left, right) => {
if (typeof left !== "object" || left === null) return false;
let proto = left.__proto__;
while (proto) {
if (proto === right.prototype) {
return true;
}
proto = myInstanceiof1(proto);
}
return false;
};
2.使用Object.getPrototypeOf
实现
const myInstanceiof = (left, right) => {
if (typeof left !== "object" || left === null) return false;
let proto = Object.getPrototypeOf(left); //返回指定对象的原型
while (true) {
if (proto === null) {
return false;
}
if (proto === right.prototype) return true;
proto = Object.getPrototypeOf(proto);
}
};
test
let obj = { name: "jane" };
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
console.log(obj instanceof Object, obj instanceof Person); //true false
console.log(
myInstanceiof1(obj, Object),
myInstanceiof1(obj, Person)
);
网友评论