instanceof 的使用和实现

151 阅读1分钟

instanceof的使用

instanceof主要用来判断一个对象是否是另一个对象的子类。通常用于判断是否是 new 构造出来的对象。 注意 由于原型链 所以最终会往上找到Object上去 而Object再往上走 就是 null

let a = [1];
a instanceof Array // true;
a instanceof Object // true;
function F(){};
let f = new F();
f instanceof F; // true
f instanceof Object; // true

instanceof的原生实现

function myInstanceOf(left, right) {
    if(typeof left !== 'object' || left === null) {
        return false;
    }
    // 获取 left的原型
    let proto = Object.getPrototypeOf(left);
    while(true) {
        if(proto === null) {
            return false;
        }
        if(proto === right.prototype) {
            return true;
        }
        proto = Object.getPrototypeOf(proto);
    }
}