js手写系列 【instanceof】

119 阅读1分钟

instanceof

instanceof的作用

判断一个实例是否是其父类或者祖先类型的实例,instanceof 在查找的过程中会遍历左边变量的原型链,直到找到与右边变量的 prototype相等的原型,找到则返回true, 否则返回false

手写instanceof

function myInstanceOf(target, origin) {
    // 循环遍历目标对象的原型链
    while (target) {
        // 判断target的原型是否是origin的实例对象
        if (target.__proto__ === origin.prototype) {
            // 是,则返回true
            return true;
        }
        // 否则让target等于其原型
        target = target.__proto__;
    }
    // 若target的原型不存在了,则返回false
    return false;
}

// 测试
let a = [1, 2, 3];
console.log(myInstanceOf(a, Array)); // true
console.log(myInstanceOf(a, Object)); // true
console.log(myInstanceOf(a, Number)); // false