instanceof原理
instance instanceof construtor
instanceof 会遍历instance的原型链,判断 construtor的原型是否在instance的原型链上。原理就是这么简单,但是需要先理解原型与原型链。
实现
在这之前有两个问题:
- 如何获取
instance的原型链? - 如何判断
instance的原型链的终点?
对于第一个问题,对象都有个__proto__属性,更准确的应该称之为访问器属性(getter/setter)。更详细的看这里,由于该属性已经从 Web标准中删除,所以我们使用 Object.getPrototypeOf(),该函数可以获取对象的原型对象。
Object.getPrototypeOf([]) === Array.prototype // true
Object.getPrototypeOf(new Date()) === Date.prototype // true
对于第二个问题,所有对象原型链的都终结于Object.prototype,而 Object.getPrototypeOf(Object.prototype) === null,所以我们只要判断Object.getPrototypeOf(instance) === null即可。
function myInstanceOf(instance, construtor){
if(instance == null){
return false;
}
//第一个原型对象
let prototype = Object.getPrototypeOf(instance);
while(prototype !== null){
//当前原型对象是否与构造函数的原型对象相同
if(prototype === construtor.prototype){
return true;
}
//下一个原型对象
prototype = Object.getPrototypeOf(prototype);
}
return false;
}
测试一下
//利用原型链实现继承
function Parent(){}
function Child(){
Parent.call(this);
}
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
const child = new Child();
console.log(myInstanceOf(child, Child));//true
console.log(myInstanceOf(child, Parent));//true
console.log(myInstanceOf(child, Object));//true
console.log(myInstanceOf(child, Array));//false