手动实现function isInstanceOf(child,Parent)

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

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值