首页 > jquery中的type实现

jquery中的type实现

在jquery源码中:

javascripttype: function( obj ) {
    if ( obj == null ) {
        return obj + "";
    }
    // Support: Android<4.0, iOS<6 (functionish RegExp)
    return typeof obj === "object" || typeof obj === "function" ?
        class2type[ toString.call(obj) ] || "object" :
        typeof obj;
},

// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
    class2type[ "[object " + name + "]" ] = name.toLowerCase();
});

既然使用class2type就能检测出除undefined和null所有的类型,为什么jquery只有在 typeof obj === "object" || typeof obj === "function"才使用class2type,其他的类型依然使用typeof

为了更快的速度么?使用typeof能直接输出结果,而class2type还得调用内部属性,再转成字符串?

谢谢各位。


先看一段代码

function printType(obj) {
    console.log(typeof obj, toString.call(obj));
}

printType("hello");
printType(2);
printType(2.3);
printType(true);
printType(function() {});

printType(new String("hello"));
printType(new Number(2));
printType(new Number(2.3));
printType(new Boolean(true));
printType(new Function());

结果

string [object String]
number [object Number]
number [object Number]
boolean [object Boolean]
function [object Function]
object [object String]
object [object Number]
object [object Number]
object [object Boolean]
function [object Function]

其实大部分是可以用 typeof 来获得结果的,而且相比用 toString.call 来获得更快。但是有一些对象需要特殊处理,主要就是 new String()new Number()new Boolean() 等(观察后面几行的结果)

【热门文章】
【热门文章】