几行代码实现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继承
推荐阅读
- CVE-2020-16898|CVE-2020-16898 TCP/IP远程代码执行漏洞
- 关于QueryWrapper|关于QueryWrapper,实现MybatisPlus多表关联查询方式
- MybatisPlus使用queryWrapper如何实现复杂查询
- python学习之|python学习之 实现QQ自动发送消息
- 孩子不是实现父母欲望的工具——林哈夫
- opencv|opencv C++模板匹配的简单实现
- Node.js中readline模块实现终端输入
- java中如何实现重建二叉树
- 不废话,代码实践带你掌握|不废话,代码实践带你掌握 强缓存、协商缓存!
- 人脸识别|【人脸识别系列】| 实现自动化妆