当前位置:网站首页>Manually implement function isinstanceof (child, parent)
Manually implement function isinstanceof (child, parent)
2022-07-01 21:36:00 【Yiyao Bingo】
List of articles
1-1 instance Main functions and use
Determine whether an instance belongs to a certain type
let person = function(){
}
let no = new person();
no instanceof person; // true
1-2 insInstanceOf principle
Before understanding the principle and hand code , Need to know JS Prototype chain : JS Prototype chain
1、 The main implementation principle : Just the variables on the right prototype On the prototype chain of the left variable
- so,instanceof In the process of searching, we will traverse the prototype chain of variables on the left , Until you find the... Of the variable on the right prototype
- To find the failure , return false, That is, the left variable is not an instance of the right variable
2、
function new_instanceOf(leftValue, rightValue) {
let rightValue = rightValue.prototype; // Take... Of the right expression prototyoe value
leftValue = leftValue.__proto__;
while (true) {
if (leftValue === rightProto) {
return true;
}
if (leftValue === null) {
return false;
}
leftVaule = leftVaule.__proto__ ;
}
}
1-3 Manual code and test stage
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__;
}
}
// Start testing
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
边栏推荐
猜你喜欢
随机推荐
统计字符中每个字符出现的个数
新版Free手机、PC、平板、笔记本四端网站缩略展示图在线一键生成网站源码
游览器打开摄像头案例
Review notes of Zhang Haifan in introduction to software engineering (Sixth Edition)
杰理之、产线装配环节【篇】
一次调试去了解redis集群的slot机制
打出三位数的所有水仙花数「建议收藏」
【Opencv450】HOG+SVM 与Hog+cascade进行行人检测
NSI脚本的测试
How to connect the two nodes of the flow chart
Practical project notes (I) -- creation of virtual machine
Gaussdb (for MySQL):partial result cache, which accelerates the operator by caching intermediate results
杰理之烧录上层版物料需要【篇】
编译原理复习笔记
PMP证书真的有用吗?
同花顺股票开户选哪个券商好手机开户是安全么?
Kuberntes云原生实战一 高可用部署架构
Target detection - Yolo series
极客DIY开源方案分享——数字幅频均衡功率放大器设计(实用的嵌入式电子设计作品软硬件综合实践)
Oracle deadlock test