JavaScript uses typeof to judge whether it is an object's disadvantage

Title: use typeof bar === "object" to determine whether bar is the potential trap of an object? How to avoid this trap?

 

1: Using typeof

 

First look at the following code:

var carr=[];
var cobj={};
function cfun(){
 console.log('cc');
}
console.log(typeof carr=='object');     //true
console.log(typeof cobj=='object');     //true
console.log(typeof cfun=='function');   //true
console.log(typeof null=='object');     //true

As you can see, typeof null is also "object", which is generally not what we want. Whether Array and Function want to be judged as object depends on the situation.

When you want to exclude null and function, you can write as follows:

var carr=[];
var cobj={};
function cfun(){
 console.log('cc');
}

//Judge whether it is an object
function isObject(bar)
{
    if((typeof bar==='object')&&(bar!==null))
        return true;
    else
        return false;
}
console.log(isObject(carr));    //true
console.log(isObject(cobj));    //true
console.log(isObject(cfun));    //false
console.log(isObject(null));    //false

When you want to exclude null, function and Array, you can write as follows:

var carr=[];
var cobj={};
function cfun(){
 console.log('cc');
}

//Judge whether it is an object
function isObject(bar)
{
    if((typeof bar==='object')&&(bar!==null)&&(Object.prototype.toString.call(bar))!=='[object Array]')
        return true;
    else
        return false;
}

console.log(isObject(carr));    //false
console.log(isObject(cobj));    //true
console.log(isObject(cfun));    //false
console.log(isObject(null));    //false

 

2: Use toString() to detect object types

You can get the type of each object through toString(). In order for each object to be detected by Object.prototype.toString(), it needs to be called in the form of Function.prototype.call() or Function.prototype.apply(), passing the object to be checked as the first parameter. The results are clear.

var carr=[];
var cobj={};
function cfun(){
 console.log('cc');
}

var toString = Object.prototype.toString;

console.log(toString.call(new Date)); // [object Date]
console.log(toString.call(new String)); // [object String]
console.log(toString.call(Math)); // [object Math]

console.log(toString.call(undefined)); // [object Undefined]
console.log(toString.call(null)); // [object Null]

console.log(toString.call(carr)); // [object Array]
console.log(toString.call(cobj)); // [object Object]
console.log(toString.call(cfun)); // [object Function]

 

 

3: A more comprehensive way to detect objects (Methods in jQuery)

 

Of course, if you think the above methods are not comprehensive enough, let's see how to judge the object type in jQuery. JQuery considers all kinds of situations and the compatibility of browser versions.

Part of the code in jQuery (version 1.11.1):

var class2type = {};
var toString = class2type.toString;
var hasOwn = class2type.hasOwnProperty;
jQuery.extend({
    //Detect whether ispainobject method is used to detect whether it is a "plain object"
    //It is not DOM, and the object directly inherits Object.prototype on the prototype chain is called "plain object"
    isPlainObject: function( obj ) {
        var key;
         //Exclude non object types, then DOM objects, window objects
        if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
            return false;
        }

        try {
            // Not own constructor property must be Object
            if ( obj.constructor &&
                !hasOwn.call(obj, "constructor") &&
                !hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
                return false;
            }
        } catch ( e ) {
            // IE8,9 Will throw exceptions on certain host objects #9897
            return false;
        }
        //Compatible with older browsers
        // Support: IE<9
        // Handle iteration over inherited properties before own properties.
        if ( support.ownLast ) {
            for ( key in obj ) {
                return hasOwn.call( obj, key );
            }
        }
        // Own properties are enumerated firstly, so to speed up,
        // if last one is own, then all properties are own.
        for ( key in obj ) {}

        return key === undefined || hasOwn.call( obj, key );
    },

    type: function( obj ) {
        if ( obj == null ) {
            return obj + "";
        }
        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();
});

 

Keywords: JQuery IE

Added by andyjimmy on Sat, 01 Feb 2020 04:18:40 +0200