typeof和instanceof实现原理

304 阅读1分钟

typeof

typeof是判断基本类型的,基本类型有7种: Undefined, null, Boolean, Number, String, bigint, symbol,还能判断出function 然后其他都是object(null是object);

function myTypeOf(params) {
    const type = Object.prototype.toString.call(params).slice(8, -1).toLowerCase();
    const map = { 
        'number': true, 
        'string': true, 
        'boolean': true, 
        'undefined': true, 
        'bigint': true, 
        'symbol': true, 
        'function': true 
    }
    return map[type] ? type : 'object';
}

instanceof

function myInstanceOf(obj, Fn) { 
    if (typeof obj !== 'object') return false;
    const structure = obj.__proto__;
    if (structure === null) return false;
    if (structure !== Fn.prototype) { 
        return myInstanceof(structure, Fn) 
    } else { 
        return true 
    } 
}

总结:typeof只能判断简单的数据类型;instanceof不能精确区分[]、{}、new Date()、new RegExp()(xx instanceof Object),都返回true。所以可以使用Object.prototype.toString.call。