实例对象 instanceof 构造函数

    构造函数的原型是否在实例对象的原型链上

    1. function myInstanceof(obj, constructor) {
    2. return constructor.prototype.isPrototypeOf(obj);
    3. }
    1. function myInstanceof(obj, constructor) {
    2. // obj 数据类型
    3. if((typeof obj !== 'object' && typeof obj !== 'function') || obj === null) return false;
    4. let proto = Object.getPrototypeOf(obj);
    5. while (proto) {
    6. if (proto === constructor.prototype) return true;
    7. proto = Object.getPrototypeOf(proto);
    8. }
    9. return false;
    10. }

    测试

    1. [] instanceof Array // true
    2. myInstanceof([], Array); // true
    3. const obj = Object.create(null);
    4. obj instanceof Object // false
    5. myInstanceof(obj, Object); // false
    6. 1 instanceof Object // false
    7. myInstanceof(1, Object); // false
    8. function func() {}
    9. func instanceof Function // true
    10. myInstanceof(func, Function); // true