实例对象 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 // truemyInstanceof([], Array); // trueconst obj = Object.create(null);obj instanceof Object // falsemyInstanceof(obj, Object); // false1 instanceof Object // falsemyInstanceof(1, Object); // falsefunction func() {}func instanceof Function // truemyInstanceof(func, Function); // true
