- 首先 instanceof 左侧必须是对象, 才能找到它的原型链
- instanceof 右侧必须是函数, 函数才会prototype属性
- 迭代 , 左侧对象的原型不等于右侧的 prototype时, 沿着原型链重新赋值左侧
function isObject(obj){
return typeof obj === 'object' && obj != null
}
//手写instanceof
function myInstanceof (l,r) {
// 判断是否为对象
if (!isObject(l) && !isObject(r)) return false
// 先获取r的显式原型
let rp = r.prototype
// 先获取l的隐式原型
let lr = l.__proto__
while(true){
if (lr === null) {
return false
}
if (lr === rp) {
return true
}
lr = lr.__proto__
}
}