几行代码实现instanceof

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// true ming 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原型、原型链
【几行代码实现instanceof】手撕js继承

    推荐阅读