当前位置:网站首页>手动实现function isInstanceOf(child,Parent)
手动实现function isInstanceOf(child,Parent)
2022-07-01 21:32:00 【翼遥bingo】
1-1 instance主要作用及使用
判断一个实例是否属于某种类型
let person = function(){
}
let no = new person();
no instanceof person; // true
1-2 insInstanceOf原理
在了解原理及手撸代码之前,需要了解JS原型链: JS原型链
1、 主要实现原理: 只要右边变量的prototype在左边变量的原型链上即可
- so,instanceof在查找的过程中会遍历左边变量的原型链,直到找到右边变量的prototype
- 查找失败,返回false,即左边变量并非右边变量的实例
2、
function new_instanceOf(leftValue, rightValue) {
let rightValue = rightValue.prototype; // 取右表达式的prototyoe值
leftValue = leftValue.__proto__;
while (true) {
if (leftValue === rightProto) {
return true;
}
if (leftValue === null) {
return false;
}
leftVaule = leftVaule.__proto__ ;
}
}
1-3 手撸代码及测试阶段
function instance_of(l,r) {
let rProto = r.prototype;
let lValue = l.__proto__;
while(true) {
if (lValue === null) {
return false;
}
if (lValue === rProto) {
return true;
}
lValue = lValue.__proto__;
}
}
// 开始测试
var a = []
var b = {
}
function Foo(){
}
var c = new Foo()
function child(){
}
function father(){
}
child.prototype = new father()
var d = new child()
console.log(instance_of(a, Array)) // true
console.log(instance_of(b, Object)) // true
console.log(instance_of(b, Array)) // false
console.log(instance_of(a, Object)) // true
console.log(instance_of(c, Foo)) // true
console.log(instance_of(d, child)) // true
console.log(instance_of(d, father)) // true

边栏推荐
- Importance of EDA tools to chip industry knowledge popularization
- Big factories are wolves, small factories are dogs?
- 目标检测——Yolo系列
- BC35&BC95 ONENET MQTT(旧)
- Exclusive news: Alibaba cloud quietly launched RPA cloud computer and has opened cooperation with many RPA manufacturers
- burpsuite简单抓包教程[通俗易懂]
- 想请教一下,券商选哪个比较好尼?本人小白不懂,现在网上开户安全么?
- Past and present life of product modular design
- leetcode刷题:栈与队列03(有效的括号)
- Internship: complex JSON format data compilation interface
猜你喜欢
随机推荐
人才近悦远来,望城区夯实“强省会”智力底座
面试题:MySQL的union all和union有什么区别、MySQL有哪几种join方式(阿里面试题)[通俗易懂]
杰理之蓝牙耳机品控和生产技巧【篇】
4. 对象映射 - Mapping.Mapstercover
游览器打开摄像头案例
C中main函数的几种写法
Richview RichEdit srichviewedit PageSize page setup and synchronization
MQ学习笔记
PHP 读取ini或env类型配置
Principle of motion capture system
Gaussdb (for MySQL):partial result cache, which accelerates the operator by caching intermediate results
What else do you not know about new set()
leetcode刷题:栈与队列04(删除字符串中的所有相邻重复项)
Slf4j打印异常的堆栈信息
杰理之、产线装配环节【篇】
Importance of EDA tools to chip industry knowledge popularization
GCC编译
安装mysql时出现:需要这两个包perl(Data::Dumper),perl(JSON)
目标检测——Yolo系列
在技术升级中迎合消费者需求,安吉尔净水器“价值战”的竞争之道









