instanceof原理

71 阅读1分钟

instanceof原理

什么是instanceof

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

 // AB的实例,返回true,否则返回false
 // 判断A的原型链上是否有B的原型
 A instanceof B

模拟实现

思路:沿原型链往上查找

 function instance_of(left, right){
     //排除基本数据类型
     if((typeof left !== 'object' && typeof left !== 'function') || left === null) return false
     const rightPrototype = right.prototype
     // 获取实例对象的隐式原型
     let CaseProto = Object.getPrototypeOf(Case)
     while(1){
         // 说明到原型链顶端,还未找到,返回 false
         if(CaseProto === null) return false
         // 发现原型链中存在构造函数的 prototype 属性,返回true
         if(CaseProto === rightPrototype) return true
         // 沿着原型链向上找
         CaseProto = Object.getPrototypeOf(CaseProto)
     }
 }