在jquery源码中:
javascript
type: 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
还得调用内部属性,再转成字符串?
谢谢各位。
先看一段代码
结果
其实大部分是可以用
typeof
来获得结果的,而且相比用toString.call
来获得更快。但是有一些对象需要特殊处理,主要就是new String()
和new Number()
、new Boolean()
等(观察后面几行的结果)