手写实现instanceof

137 阅读1分钟

每天做个总结吧,坚持就是胜利!

    /**
        @date 2021-06-14
        @description 手写实现instanceof
    */

壹(序)

instanceof是一个运算符,用来判断构造函数的prototype是否在某个实例对象的原型链上。

贰(使用)

function Person() {
    this.type = 'person';
}
const p = new Person(); // Person {type: "person"}
p instanceof Person; // true

叁(代码实现)

function instanceOf(obj, ctor) {
    if(typeof obj !== 'object' || typeof obj === null){
        return false
    }   
    
    let proto = Object.getPrototypeOf(obj);

    while(true) {
        if(proto === ctor.prototype) {
            return true
        }

        if(proto === null) {
            return false
        }

        proto = Object.getPrototypeOf(proto)   
    }
}

// 测试
function Person(name) {
    this.name = name;
}

const p = new Person('E1e');
const obj = {};
const arr = [];

instanceOf(p, Person); // true
instanceOf(obj, Person); // false
instanceOf(arr, Person); // false
instanceOf(p, Object); // true
instanceOf(arr, Array); // true

肆(结语)

祝大家端午安康!