手写 instanceof

100 阅读1分钟

instaceof:判断A是否为B的实例

知识点:如果A沿着原型链能找到B.prototype,那么A instaceof B为true

解法:遍历A的原型链,如果能找到B.prototype,返回true,循环结束返回false

function Instanceof(A, B) {
    let p = A;
    while (p) {
        if (p === B.prototype) return true;
        p = p.__proto__;
    }
    return false;
}
const arr = [];
console.log("result", Instanceof(arr, Array)); // true