关于前端:几行代码实现instanceof

6次阅读

共计 688 个字符,预计需要花费 2 分钟才能阅读完成。

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 原型、原型链

手撕 js 继承

正文完
 0