当前位置:网站首页>手动实现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
边栏推荐
- 【mysql 07】GPG key retrieval failed: “Couldn‘t open file /etc/pki/rpm-gpg/RPM-GPG-KEY-mysql-2022“
- EURA eurui E1000 series inverter uses PID to realize the relevant parameter setting and wiring of constant pressure water supply function
- Penetration tools - trustedsec's penetration testing framework (PTF)
- ngnix基础知识
- Using qeventloop to realize synchronous waiting for the return of slot function
- 2022安全员-A证考题及在线模拟考试
- 【STM32】STM32CubeMX教程二–基本使用(新建工程点亮LED灯)
- 人才近悦远来,望城区夯实“强省会”智力底座
- Internship: complex JSON format data compilation interface
- leetcode刷题:栈与队列04(删除字符串中的所有相邻重复项)
猜你喜欢
随机推荐
Halcon知识:三维重构的一个尝试
MQ学习笔记
功利点没啥!
寫博客文檔
最近公共祖先离线做法(tarjan)
多个张量与多个卷积核做卷积运算的输出结果
从20s优化到500ms,我用了这三招
杰理之、产线装配环节【篇】
Internship: complex JSON format data compilation interface
Principle of motion capture system
朋友圈社区程序源码分享
面试题:MySQL的union all和union有什么区别、MySQL有哪几种join方式(阿里面试题)[通俗易懂]
cmake工程化相关
How to create a pyramid with openmesh
There are four ways to write switch, you know
薛定谔的日语学习小程序源码
杰理之烧录上层版物料需要【篇】
王者战力查询改名工具箱小程序源码-带流量主激励广告
Richview RichEdit srichviewedit PageSize page setup and synchronization
合成大西瓜小游戏微信小程序源码/微信游戏小程序源码