# instance of 原理

顾名思义 a 是不是 b 的实例对象

function instance_of(left, right) {
  let rightPrototype = right.prototype;
  left = left.__proto__;
  while (true) {
    if (left === null) {
      return false;
    }
    if (left === rightPrototype) {
      return true;
    }
    left = left.__proto__;
  }
}

var a = [] 
//测试
a instanceof Array //true
instance_of(a,Array) //true


//缺陷是:可以更改a.__proto__对象导致instance_of返回错误
a.__proto__ = String;
a instanceof Array //false
instance_of(a,Array) //false

//判断类型终极解决办法
Object.prototype.toString.call(a) === '[object Array]';

Last Updated: 5/22/2022, 3:57:36 PM