Shaoli's Blog

三、手写源码之 instanceof

instanceof 运算符用于测试构造函数的 prototype 属性是否出现在对象原型链中的任何位置。


实现思路:

首先 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
}


如有不足,麻烦指出~

    评论列表

  • 暂无评论...快来说说吧!
person
0 / 16
comment
0 / 100