实例对象 instanceof 构造函数
构造函数的原型是否在实例对象的原型链上
function myInstanceof(obj, constructor) {
return constructor.prototype.isPrototypeOf(obj);
}
function myInstanceof(obj, constructor) {
// obj 数据类型
if((typeof obj !== 'object' && typeof obj !== 'function') || obj === null) return false;
let proto = Object.getPrototypeOf(obj);
while (proto) {
if (proto === constructor.prototype) return true;
proto = Object.getPrototypeOf(proto);
}
return false;
}
测试
[] instanceof Array // true
myInstanceof([], Array); // true
const obj = Object.create(null);
obj instanceof Object // false
myInstanceof(obj, Object); // false
1 instanceof Object // false
myInstanceof(1, Object); // false
function func() {}
func instanceof Function // true
myInstanceof(func, Function); // true