首先 instanceof 左侧必须是对象, 才能找到它的原型链,
instanceof 右侧必须是函数, 函数才会prototype属性,
迭代 , 左侧对象的原型不等于右侧的 prototype时, 沿着原型链重新赋值左侧。
// 右边的原型是否在左边的原型链上
function instanceOF(l, r) {
const basicTypes = ['string', 'number', 'boolean', 'undefined']
if(basicTypes.includes(typeof l)) {
return false
}
let leftVal = l.__proto__
const rightVal = r.prototype
while(true) {
if(leftVal === null) {
return false
}
if(leftVal === rightVal) {
return true
}
leftVal = leftVal.__proto__
}
}
console.log(instanceOF([1,2,3], Array)) // true
另一种写法
function instanceOF2(l, r) {
if (typeof l !== 'object') { return false }
let leftVal = Object.getPrototypeOf(l)
const rightVal = r.prototype
while (leftVal !== null) {
if (leftVal === rightVal) {
return true
}
leftVal = Object.getPrototypeOf(leftVal)
}
return false
}
如有不足,麻烦指出~
©2018-2020 hongshali.com 版权所有 ICP证:闽ICP备18029655号-1