手写 JavaScript 的 instanceof

33 阅读1分钟

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

instanceof 的用法

{
    const obj = {};
    console.log(obj instanceof Object); // true
}

instanceof 的实现

function myInstanceof(obj, constructor) {
    let implicitPrototype = obj?.__proto__;
    const displayPrototype = constructor.prototype;

    while (implicitPrototype) {
        if (displayPrototype === implicitPrototype) {
            return true;
        }

        implicitPrototype = implicitPrototype.__proto__;
    }

    return false;
}

const obj = {};
console.log(myInstanceof(obj, Object)); // true