ChuChencheng / note

菜鸡零碎知识笔记
Creative Commons Zero v1.0 Universal
3 stars 0 forks source link

JavaScript 实现 instanceof 运算符 #12

Open ChuChencheng opened 4 years ago

ChuChencheng commented 4 years ago

定义

检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上。

实现

  1. 先判断构造函数是否合法
  2. 在实例的原型链上查找是否有等于 F.prototype 的原型
function _instanceof (instance, constructor) {
  if (typeof constructor !== 'function') {
    throw new TypeError(`Right-hand side of 'instanceof' is not callable`)
  }
  const isPrimitive = (value) => value == null || (typeof value !== 'object' && typeof value !== 'function')
  const constructorPrototype = constructor.prototype
  let prototype = instance
  while (!isPrimitive(prototype)) {
    prototype = Object.getPrototypeOf(prototype)
    if (prototype === constructorPrototype) return true
  }
  return false
}