instanceof 的用法
MDN:
instanceof 运算符用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上。
// 构造函数
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
// 实例对象
let car1 = new Car('大众', 'polo', 2021)
car1 instanceof Car // true,因为 Object.getPrototypeOf(car1) === Car.prototype
// Object.getPrototypeOf(car1) 返回指定对象的原型,是ES5的方法,相当于car1.__proto__
手动实现instanceof
/* 思路:
先比较实例对象的原型等不等于构造函数的prototype,
如果等于,则返回true
如果不等于,则找实例对象原型的原型,比较它等不等于构造函数的prototype,
如果等于,则返回true
如果不等于,则继续在原型链往上找,直到找到原型链的最顶层,即null,则为false
*/
function myInstanceof(obj, fn) {
let prototype = fn.prototype;
let proto = Object.getPrototypeOf(obj);
while(true) {
if(proto === null) {
return false
} else if (proto === prototype) {
return true
}
proto = Object.getPrototypeOf(proto)
}
}
// 用一下试试
myInstanceof(car1, Car) // true