浅谈如何实现一个 instanceof 方法

301 阅读1分钟

instanceof():instanceof 运算符用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上。
原型链:

image.png

image.png

构造函数       原型对象
  
       实例对象
function myInstanceOf(left, right) {
//实例对象 构造函数
    if (typeof left !== 'object' || left == null) {
        return false;
    }
    
    let pro = Object.getPrototypeOf(left);
    while(true) {
        if (pro === null) {
            return false;
        }
        if (pro === right.prototype) {
            return true;
        }
        pro = Object.getPrototypeOf(pro);//**`Object.getPrototypeOf()`** 方法返回指定对象的原型 ( 即, 内部[[Prototype]]属性)。
    }
}

function Car(make, model, year) {  //构造函数
  this.make = make;
  this.model = model;
  this.year = year;
}
const auto = new Car('Honda', 'Accord', 1998);   //实例对象

console.log(myInstanceOf(auto,Car));
// expected output: true

console.log(myInstanceOf(auto,Object));
// let obj = new myInstanceOf()

这里的源码来自于大厂面试及答案整理 (juejin.cn),侵删
再次强调:instanceof():instanceof 运算符用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上。