手写instanceof

129 阅读1分钟

instanceof

A instancof B用于判断A是否出现在B的原型链上。可以用于判断引用数据类型,返回一个布尔值

手写instanceof原理

  1. 定义一个函数,参数为instanceof的左边和右边。left 和right
  2. 保存left的隐式原型属性。因为要沿着隐式原型链不断向上寻找,如果能够在right的显示原型对象中找到,返回true
  3. while循环,如果隐式原型属性没有找到null进入循环,如果沿着隐式原型链可以找到right.prototype,返回true,否则一直沿着原型链向上寻找。直到找到null,跳出循环,返回false;
function myInstance(left, right) {
  if (Object(left) !== left) return false
  let proto = left.__proto__;
  while (proto !== null) {
    if (proto === right.prototype) return true
    proto = proto.__proto__
  }
  return false;
}