有趣的代码: fixTypeof

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


    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)方法prototype

相关文章
相关标签/搜索