有趣的代码: fixTypeof

typeof 可以匹配对象的类型,但是他的能力很弱,比如 typeof new String('123')会显示的object这是我们不想看到的结果很久以前JQ的作者通过Object.prototype.toString.call(name)这逆天的方法帮我们指明的道路.


    function fixTyoeof(obj){
        var retVal;
        //由于typeof null 也会是object我们这里去排除
        if(obj === null)
            return 'null';
        //Math我们也去排除
        if(obj === Math)
            return 'Math';
        retVal = typeof obj
        if(retVal === 'object'){
            switch(obj.constructor){
                case String:
                    return 'string';
                case Number:
                    return 'number';
                case Boolean:
                    return 'boolean';
                case Array:
                    return 'array';
                case Date:
                    return 'date';
                case RegExp:
                    return 'regExp';
            }
        }
        return retVal;
    }
function fixTyoeof(key){
    switch(Object.prototype.toString.call(key)){
        case '[object Array]'         : return 'Array';
        case '[object String]'         : return 'String';
        case '[object RegExp]'         : return 'RegExp';
        case '[object Number]'         : return 'Number';
        case '[object Function]'    : return 'Function';
        case '[object Boolean]'     : return 'Boolean';
        case '[object Math]'        : return 'Math';
        case '[object Date]'        : return 'Date';
        default :
            //由于 IE678 null undefined 会显示[object Object] 所以我们直接匹配
            switch(key){
                case null             : return 'Null';
                case undefined         : return 'Undefined';
                default             : return 'Object';
            }
    }
}

第一版是通过 constructor 去识别,第二版是通过逆天的Object.prototype.toString.call(name)方法

原文地址:https://www.cnblogs.com/somesayss/p/3633197.html