前端跳槽每日一题之 instanceof

62 阅读1分钟

1 instanceof

instanceof 运算符用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上。

2 手写 instanceof

function myInstanceof(constructor, object) {
    const prototype = constructor.prototype;
    let proto = Object.getPrototypeOf(object);
    while(true) {
        if(!proto) { return false; }
        if(proto===prototype) { return true; }
        proto = Object.getPrototypeOf(proto);;
    }
}

image.png