《instanceof》

31 阅读1分钟

手写instanceof

function _instanceof(A, B) {
  let flag = false;
  let prototype = Object.getPrototypeOf(A);
  // 获取A的原型对象
  while (prototype) {
    if (prototype === B.prototype) {
      flag = true;
      break;
    }
    prototype = Object.getPrototypeOf(prototype);
  }
  return flag;
}

function Person() {}
var p = new Person()

p instanceof Person  // true  
p instanceof Object  // true  
p instanceof Array   // false

_instanceof(p, Person)  // true
_instanceof(p, Object)  // true
_instanceof(p, Array)   // false