js instanceof原理,并用代码表示

instanceof原理: 例如 f instanceof Foo,顺着f.__proto__向上查找,看能否找到Foo.prototype
找到返回true 找不到返回false。
所有值类型都是返回false,例如 :

'abc' instanceof String  //false
 123 instanceof Number  //false

图例:
在这里插入图片描述
代码示例:

function myInstanceof(instance: any, origin: any): boolean{
	if(instance == null) return false
	
	const type = typeof instance
	if(type !== 'object' && type !== 'function') {
		// 所有值类型 返回都是false
		return false
	}

	let tempInstance = instance
	while(tempInstance) {
		if(tempInstance.__proto__ === origin.prototype){
			return ture
		}
		// 未匹配上 顺着原型链网上继续找
		tempInstance = tempInstance.__proto__
	}
	return false
}

// 测试
console.log(myInstanceof(null,Object)) // false
console.log(myInstanceof(123,Number))// false
console.log(myInstanceof('abc',String))// false
console.log(myInstanceof({},Object)) // true
console.log(myInstanceof([],Array))// true

function fn(){}
console.log(myInstanceof(fn,Function))// true

class Foo {}
const f = new Foo()
console.log(myInstanceof(f,Foo)) // true
console.log(myInstanceof(f,Object)) // true
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值