Search code examples
javascriptfunctionobject

IsPlainObject, thing?


Does this fn:

function isplainobj ( obj ) {
    return Object.prototype.toString.call( obj ) === "[object Object]";
}

do the same thing as jQuery's: $.isPlainObject() ?


Solution

  • No, it doesn't.

    Here is it's implementation:

    isPlainObject: function( obj ) {
        var key;
    
        // Must be an Object.
        // Because of IE, we also have to check the presence of the constructor property.
        // Make sure that DOM nodes and window objects don't pass through, as well
        if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
            return false;
        }
    
        try {
            // Not own constructor property must be Object
            if ( obj.constructor &&
                !core_hasOwn.call(obj, "constructor") &&
                !core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
                return false;
            }
        } catch ( e ) {
            // IE8,9 Will throw exceptions on certain host objects #9897
            return false;
        }
    
        // Support: IE<9
        // Handle iteration over inherited properties before own properties.
        if ( jQuery.support.ownLast ) {
            for ( key in obj ) {
                return core_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 || core_hasOwn.call( obj, key );
    },
    

    It checks if it's type is object, if it has or not a constructor and if its properties are own properties.

    For example with your function an instance of a class will return true but in this case, because it has a constructor it will return false.