当前位置:网站首页>手动实现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

边栏推荐
- 【opencv】train&test HOG+SVM
- 十三届蓝桥杯B组国赛
- 编译原理复习笔记
- 从20s优化到500ms,我用了这三招
- 面试题:MySQL的union all和union有什么区别、MySQL有哪几种join方式(阿里面试题)[通俗易懂]
- 实战项目笔记(一)——虚拟机的创建
- 8K HDR!| Hevc hard solution for chromium - principle / Measurement Guide
- 图片拼图微信小程序源码_支持多模板制作和流量主
- js如何获取集合对象中某元素列表
- Niuke programming question -- must brush the string of 101 (brush the question efficiently, draw inferences from one instance)
猜你喜欢

4. 对象映射 - Mapping.Mapstercover

leetcode刷题:栈与队列07(滑动窗口最大值)

MySQL数据库驱动(JDBC Driver)jar包下载

多个张量与多个卷积核做卷积运算的输出结果

基于K-means的用户画像聚类模型

Kuberntes云原生实战一 高可用部署架构

升级版手机检测微信工具小程序源码-支持多种流量主模式

2022年高处安装、维护、拆除考题模拟考试平台操作

【智能QbD风险评估工具】上海道宁为您带来LeanQbD介绍、试用、教程

Penetration tools - trustedsec's penetration testing framework (PTF)
随机推荐
杰理之、产线装配环节【篇】
深度学习 神经网络基础
柒微自动发卡系统源码
PHP 读取ini或env类型配置
2022熔化焊接与热切割上岗证题目模拟考试平台操作
架构师毕业总结
How to create a pyramid with openmesh
【Opencv450】HOG+SVM 与Hog+cascade进行行人检测
薛定谔的日语学习小程序源码
burpsuite简单抓包教程[通俗易懂]
How to connect the two nodes of the flow chart
关联线探究,如何连接流程图的两个节点
Gaussdb (for MySQL):partial result cache, which accelerates the operator by caching intermediate results
leetcode刷题:二叉树03(二叉树的后序遍历)
多个张量与多个卷积核做卷积运算的输出结果
【opencv】train&test HOG+SVM
以飞地园区为样本,看雨花与韶山如何奏响长株潭一体化发展高歌
人才近悦远来,望城区夯实“强省会”智力底座
Écrire un document de blog
最近公共祖先离线做法(tarjan)