手写instanceof关键字

183 阅读1分钟

手写instanceof关键字

instanceof实现原理是通过原型链判断的,我们拿到instanceof左侧对象的原型链,拿到instanceof右侧对象的显示原型prototype

如果原型链中存在显示原型prototype,那么就返回true,反之返回false,instanceof关键字不适用于基本数据类型

function myinstanceof(left, right) {
  //如果left不是对象,则直接返回false
  if(typeof left !== 'object' || left == null) return false
  
  let leftProto = left.__proto__;
  let rightPrototype = right.prototype;
  
  while (true) {
    if (leftProto === null) {
      //到了原型链顶端还没有找到
      return false;
    }
    if (leftProto === rightPrototype) {
      //找到了
      return true;
    }
    //此处类似递归,一旦不满足两个if就将leftProto更新
    leftProto = leftProto.__proto__;
  }
}

测试用例

let a = 'abc'
console.log(myinstanceof(a ,String));//false
console.log(a instanceof String);//false

let b = {}
console.log(myinstanceof(b ,Object));//true
console.log(b instanceof Object)//true

let c = []
console.log(myinstanceof(c ,Array));//true
console.log(c instanceof Array)//true