bojue/bojue.github.io

javaScript的instanceof实现原理

bojue opened this issue · 0 comments

bojue commented

instanceof用来检测构造函数的 prototype属性是否出现在某个实例的原型链上,MDN上的一个实例:

function Car() {
}
const auto = new Car();
console.log(auto instanceof Car); // true

我们可以判断构造函数的实例auto是又Car构造的,可以根据auto.proto === Car.prototype判断。

因为原型链的存在,我们可以顺着原型链依次判断原型链的原型,直到Object,Object的原型为null,也是我们判断的终点。

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