根据原型链和 instanceof 可以得到几个有意思的结论

109 阅读1分钟
Object instanceof Object // true
Function instanceof Function // true
Object instanceof Function // true
Function instanceof Object // true

如果只是的简单的认为instanceof就是判断谁是谁的子类的话,这里已经乱伦了

"咱俩谁管谁叫爹你管我叫爹咱俩谁管谁叫儿我管你叫儿咱俩谁是谁的爹我是你的爹咱俩谁是谁的儿你是我的儿..."

回顾下instanceof干嘛的

left.__proto__.__proto__... === Right.prototype

就记这一行伪代码就够了,instanceof就是用来判断左操作数的原型链上是否存在一个原型跟右操作数的prototype相等

function myInstanceOf(leftValue, rightValue) {
  
  let rightProto = rightValue.prototype // 取右表达式的 prototype 值
  leftValue = leftValue.__proto__ // 取左表达式的__proto__值

  while (true) {
    if (leftVaule === null) {
      return false
    }
    if (leftVaule === rightProto) { // 找到了
      return true
    }
    leftVaule = leftVaule.__proto__ // 继续找
  }
}

而原型链顶端是怎么个乱伦关系呢

根据这个图谱就能清晰的还原上面的四个判断

Object instanceof Object // true
Object.__proto__.proto__ === Object.prototype

Function instanceof Function // true
Function.__proto === Function.prototype

Object instanceof Function // true
Object.__proto__ === Function.prototype

Function instanceof Object // true
Function.__proto__.__proto__ === Object.prototype