1.首先instanceof左侧必须是对象,才能找到它的原型链 2.instanceof右侧必须是函数,函数才会prototype属性 3.迭代,左侧对象的原型不等于右侧的prototype时,沿着原型链重新赋值左侧。
function instance(left,right){
const baseType = ["string",'number','boolean','undefined','symbol']
if(baseType.includes(typeof(L)){
return false;
}
let Pright = right.prototype;
left = left.__prototype;
while(true) {
if(left === null) {
return false;
}
if(left === Pright) {
return true;
}
L = L.__proto__;
}
}
写法2
function instance2(left,right) {
if(typeof right !== 'function') throw new Error('instance error')
if(!obj || (typeof obj !== 'object' && typeof obj !== 'function') {
return false;
}
let Pright = right.prototype;
while(obj.__proto__) {
if(obj.__proto__ === proto) {
return true
}
obj = obj.__proto__
}
return false;
}
扫码加群