实现instanceof

101 阅读1分钟
// 思路:
// 1. 如果传入的实例类型不是引用类型,则直接返回false
// 2. 拿到实例的原型,判断其是否===构造函数的prototype
// 3. 如果不成立,则一直找,知道找到null退出循环并返回false


function isInstanceof(instance, Constructor) {
  if (typeof instance !== 'function'
      && (typeof instance !== 'object' || typeof instance === null)
     ) { return false }

  let proto = Object.getPrototypeOf(instance);

  while (true) {
    if (proto === null) {
      return false
    }
    if (proto === Constructor.prototype) {
      return true
    }
    proto = Object.getPrototypeOf(proto);
  }
}


function Animal(name) { this.name = name }
function Cat(name) { Animal.call(this, name) }
Cat.prototype = Object.create(Animal.prototype);
Cat.prototype.constructor = Cat;

const cat = new Cat('kimi');
console.log(isInstanceof(cat, Cat)); // true
console.log(isInstanceof(cat, Animal)); // true
console.log(isInstanceof(cat, Object)); // true