JS 手写instanceof

是我疏忽了,居然没发instanceof的。
instanceof的概念:判断右边的构造函数是否存在于左边实例的原型链上。简单来说,判断一个实例的类型是否为右边的构造函数。
原型链的理解可以看我的另一篇。
代码:

function instance_of (L, R) {
    
    
	L = L.__proto__
	while (true) {
    
    
		if (!L) return false
		if (L === R.prototype) return true
		L = L.__proto__
	}
}

function Father(name) {
    
    
  this.name = name
}

let son = new Father('snowt')

console.log(instance_of(son, Father)); // true
console.log(son instanceof Father); // true

原型链的尽头是Object.prototype.__proto__,值为null,所以循环会停止的。

おすすめ

転載: blog.csdn.net/weixin_45543674/article/details/121503951
おすすめ