undefinedfix
Sign in

Totype method in jQuery source code

rdmg edited in Sat, 16 Jul 2022

The code is as follows:

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;

}

I have tested this code several times. Arrays should have returned ["object array"], but they all returned "object". Later, I found class2type[ toString.call (obj)] always returns undefined. Does this function only work in Android < = 2.3, and in other cases, all arrays return objects?

2 Replies
aleonjhon
commented on Sun, 17 Jul 2022

JQuery source code

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 ([]); / / return arrayconsole.log (totype (null)) / / return nullconsole.log (totype (New date()) / / return dateconsole.log (totype (new number ()) / / returns the number, which is not enumerated one by one

JQuery adds this method to correctly distinguish objects. Because in JavaScript, most objects return objects using typeof. JQuery wants to distinguish these objects (if, array, date, error, regexp...)

Object . toString . call ( obj ) Can return the correct type, but the value is [ Object Array ] This kind of thing. Totype simplifies this result. Unified into a single word.

If obj is not an object or a function, that is, the basic data type, typeof can correctly return the basic data type.

Alann
commented on Sun, 17 Jul 2022
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;
}

The complete code should look like this.

When typeof obj = = = object "| typeof obj = = = = function" is true, use class2type to get the corresponding type. If it is not true, obj is an original data type, and use typeof obj to judge.

JQuery is no problem

lock This question has been locked and the reply function has been disabled.