instanceof

375 阅读1分钟

instanceof 判断数据类型

xxx instanceof xxx2 xxx到基类的原型链上 有没有 xxx2的身影

所有的引用数据类型 instanceof Object 都是true

所有值类型 instanceof 任意 都是false

自己实现一个myInstance

   function myInstance(temp, classN) {
        //temp通过__proto__向上查找时候
        //若有某次的 __proto__ ===classN.prototype 返回true
        //当某次的__proto__===null;返回false
        let str = typeof temp;
        if (str !== 'object' && str !== 'function') return false;
        var left = temp.__proto__,
            right = classN.prototype;
        // if (left === right) return true;
        while (left) {
            if (left === right) return true;
            left = left.__proto__;
        }
        return false;
    }

    function instance_of(L, R) {
        //L 表示左表达式,R 表示右表达式
        var O = R.prototype; // 取 R 的显示原型
        L = L.__proto__; // 取 L 的隐式原型
        while (true) {
            if (L === null) return false;
            if (O === L)
                // 这里重点:当 O 严格等于 L 时,返回 true
                return true;
            L = L.__proto__;
        }
    }
    [] instanceof Array; //true
    [] instanceof Object; //true
    [] instanceof Number; //false
    1 instanceof Number; //false

    myInstance([], Number);