instanceof 运算符用于检测构造函数的 prototype 属性是否呈现在某个实例对象的原型链上。

大白话就是判断某个实例是否属于某个类型或者属于它的父类、先人类...

function Parent () {    this.nums = 100}function Child (chi) {    this.chi = chi}Child.prototype = new Parent() // 原型链继承const ming = new Child('tennis')ming instanceof Child   // trueming instanceof Parent  // true

Child通过原型链继承的形式继承了Parent,所以ming不仅属于Child类型也属于Parent类型。晓得了instanceof的用法,那上面就来实现一下。

咱们要判断A是不是属于B这个类型,只须要当A的原型链上存在B即可,即A顺着__proto__向上查找,一旦能拜访到B的原型对象B.prototype,表明A属于B类型,否则的话A顺着__proto__最终会指向null。

while循环,此时此刻,非你莫属。

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

这就是instanceof的次要原理,嗯,只有这几行,超级简略,还能串联一波原型、原型链,它不香吗...

手撕js原型、原型链

手撕js继承