jquery 源码中 toType方法问题

代码如下:

function toType( obj ) {

if ( obj == null ) {
    return obj + "";
}

// Support: Android <=2.3 only (functionish RegExp)
return typeof obj === "object" || typeof obj === "function" ?
    class2type[ toString.call( obj ) ] || "object" :
    typeof obj;

}

这段代码,我测了好几遍,数组什么的本来应该返回["object array"]的,但是都是返回“object”,后来发现class2type[ toString.call( obj ) ]总是返回undefined。难道这个函数只在Android <=2.3起作用,其他情况下,数组什么的一律返回object?

阅读 2.2k
2 个回答

jquery 源码

var class2type = {};
var toString = class2type.toString;
"Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ).forEach(function(name,i){
  class2type[ "[object " + name + "]" ] = name.toLowerCase();
})
function toType( obj ) {
    if ( obj == null ) {
        return obj + "";
    }
    return typeof obj === "object" || typeof obj === "function" ?
        class2type[ toString.call( obj ) ] || "object" :
        typeof obj;
}

console.log(toType([])); // 返回array
console.log(toType(null)) //返回null
console.log(toType(new Date())) // 返回date
console.log(toType(new Number())) // 返回number
不一一枚举了

Jquery是为了正确区分对象,才加了这个方法。 因为在JavaScript中,大部分对象使用typeof 返回的是 都是object。而jquery 希望能够区分这些object (如果,Array,Date,Error,RegExp...).

Object.toString.call(obj) 能够返回正确的类型,但是值是[Object Array]这类。
toType简化了这个结果。统一为单个单词。

如果obj不是对象也不是函数,也就是基本数据类型,typeof能够正确返回基本数据的类型。

var class2type = {};
"Boolean Number String Function Array Date RegExp Object Error Symbol".split(" ").forEach(function(name,i,arr){
    class2type["[object " + name + "]"] = name.toLowerCase();
});
function toType( obj ) {
    if ( obj == null ) {
        return obj + "";
    }
    console.log(typeof obj);
    return typeof obj === "object" || typeof obj === "function" ? class2type[ {}.toString.call( obj ) ] || "object" : typeof obj;
}

完整的代码应该是这样的。

typeof obj === "object" || typeof obj === "function"成立时,就用class2type取出相应的类型,如果不成立obj就是一个原始数据类型用typeof obj判断就可以了。

jquery这种方法是没问题的

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题