instanceof 功能
a instanceof b
官方解释为检查构造函数b的prototype
有没有出现在a的原型链上。比如:
function A() {
}
function B() { }
function C() { }
//B继承A
B.prototype = new A()
let instance = new B()
console.log('---instance instanceof B-----', instance instanceof B) //true
console.log('---instance instanceof A-----', instance instanceof A) //true
手动实现
既然知道了instanceof的原理,就可以写一个函数来实现这个功能。实现过程中会用到以下两个函数中的一个。
getPrototypeOf
:获取某个实例对象的原型;
isPrototypeOf
:检测某一个对象是否存在于另一个对象的原型链上;
基于getPrototypeOf
实现的函数为:
function isInstanceOf(target1, target2) {
let proto = Object.getPrototypeOf(target1)
if(!proto){return false}
if (proto === target2.prototype) { return true }
//递归去原型链上找
return isInstanceOf(proto, target2)
}
基于isPrototypeOf
实现的函数为:
function isInstanceOf(target1, target2) {
return target2.prototypeis.isPrototypeOf(target1)
}