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继承