Skip to content

14. instanceOf实现原理

instanceOf是用来干啥的?

js
  A instanceOf B

// A必须是对象
// B是一个合法的JS函数
// 判断B的prototype是否在A的原型链上,如果在,返回true,否则为false

手写

js
  function myInstanceOf(left, right) {
    if(left == null || typeof left != 'object' || right.prototype.constructor == function) {
      throw new Error('aruments Error:left must be a Object(except null) and right must be a function')
    }
    let right_prototype = right.prototype;
    // 循环
    while(true) {
      // 遍历到Object.prototype.__proto__,即原型链结束
      if(left == null) {
        return false
      }
      // 原型链上的对象等于函数的原型对象
      if(left == right_prototype) {
        return true
      }
      left = left.__proto__
    }
  }

KESHAOYE-知识星球