当前位置:网站首页>手动实现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
边栏推荐
猜你喜欢
Learn white box test case design from simple to deep
4. 对象映射 - Mapping.Mapstercover
【深度学习】利用深度学习监控女朋友的微信聊天?
EMC-电路保护器件-防浪涌及冲击电流用
Detailed explanation and code example of affinity propagation clustering calculation formula based on graph
Niuke programming question -- must brush the string of 101 (brush the question efficiently, draw inferences from one instance)
基于YOLOv5的口罩佩戴检测方法
【智能QbD风险评估工具】上海道宁为您带来LeanQbD介绍、试用、教程
Vulnerability recurrence - Net ueeditor upload
GCC编译
随机推荐
leetcode刷题:栈与队列01(用栈实现队列)
收藏:存储知识全面总结
柒微自动发卡系统源码
8K HDR!|为 Chromium 实现 HEVC 硬解 - 原理/实测指南
Exclusive news: Alibaba cloud quietly launched RPA cloud computer and has opened cooperation with many RPA manufacturers
十三届蓝桥杯B组国赛
ngnix基础知识
以飞地园区为样本,看雨花与韶山如何奏响长株潭一体化发展高歌
编译原理复习笔记
leetcode刷题:栈与队列05(逆波兰表达式求值)
天气预报小程序源码 天气类微信小程序源码
Target detection - Yolo series
浏览器tab页之间的通信
NSI脚本的测试
MQ学习笔记
深度学习 神经网络基础
PMP证书真的有用吗?
js如何获取集合对象中某元素列表
Penetration tools - trustedsec's penetration testing framework (PTF)
Data analysts sound tall? Understand these points before you decide whether to transform