当前位置:网站首页>手动实现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
边栏推荐
- 最近公共祖先(LCA)在线做法
- PCB线路板塞孔工艺的那些事儿~
- 功利点没啥!
- EURA eurui E1000 series inverter uses PID to realize the relevant parameter setting and wiring of constant pressure water supply function
- 【深度学习】利用深度学习监控女朋友的微信聊天?
- 【opencv】train&test HOG+SVM
- Write blog documents
- 同花顺股票开户选哪个券商好手机开户是安全么?
- Uniapp uses Tencent map to select points without window monitoring to return users' location information. How to deal with it
- latex如何打空格
猜你喜欢
随机推荐
十三届蓝桥杯B组国赛
薛定谔的日语学习小程序源码
打出三位数的所有水仙花数「建议收藏」
图片拼图微信小程序源码_支持多模板制作和流量主
新版Free手机、PC、平板、笔记本四端网站缩略展示图在线一键生成网站源码
【opencv】train&test HOG+SVM
PHP gets the external chain address of wechat applet and applet store
杰理之蓝牙耳机品控和生产技巧【篇】
分离字符串中的字母和数字并使得字母在前数组在后
NSI脚本的测试
PCB线路板塞孔工艺的那些事儿~
最近公共祖先(LCA)在线做法
架构师毕业总结
强大的万年历微信小程序源码-支持多做流量主模式
最近公共祖先离线做法(tarjan)
Penetration tools - trustedsec's penetration testing framework (PTF)
Customize the insertion of page labels and realize the initial search of similar address books
能升职加薪?PMP证书含金量浅析
Spark面试题
leetcode刷题:栈与队列06(前 K 个高频元素)