提示💡

顺着原型链去找,直到找到相同的原型对象,返回 true,否则为 false

跌代实现

function myInstanceof(left, right) {
    // 这里先用typeof来判断基础数据类型,如果是,直接返回false
    if(typeof left !== 'object' || left === null) return false;
    // getProtypeOf是Object对象自带的API,能够拿到参数的原型对象
    let proto = Object.getPrototypeOf(left);
    while(true) {                  
        if(proto === null) return false;
        if(proto === right.prototype) return true;//找到相同原型对象,返回true
        proto = Object.getPrototypeof(proto);
    }
}

递归实现

function myInstanceof(target, origin) {
  const proto = Object.getPrototypeOf(target);
  if (proto) {
	if (origin.prototype === proto) {
	  return true;
	} else {
	  return myInstanceof(proto, origin)
	}
  } else {
	return false;
  }
}

测试代码

// 定义构建函数
let Car = function() {}
let benz = new Car()
myInstanceof(benz, Car) // true
let car = new String('xxx')
myInstanceof(car, String)// true
let str = 'xxx'
myInstanceof(str, String) // false