Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery + extending Object.prototype = "c.replace is not a function"

I am using jQuery 1.5 in my open source project and following line is also present in my own Javascript code:

/**
 * Object.isEmpty()
 *
 * @returns {Boolean}
 */
Object.prototype.isEmpty = function ()
{
    /**
     * @deprecated Since Javascript 1.8.5
     * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object
     */
    if ( this.__count__ !== undefined )
    {
        return this.__count__ === 0 ? true : false;
    }

    /* Less-aesthetic method, if above method fails */
    for ( var property in this )
    {
        if ( this.hasOwnProperty(property) )
        {
            return false;
        }
    }
    return true;
};

which just extends Object.prototype adding isEmpty() method to it [that checks whether the object is empty or not). Because of this addition, I am getting "c.replace is not a function" error in my Firebug console; and my research on the web lead me to jQuery bug tracker message, where I "learned" that extending Object.prototype not only breaks jQuery, but also is bad coding practice. My question is, why?

like image 663
Shahriyar Imanov Avatar asked Feb 20 '11 09:02

Shahriyar Imanov


1 Answers

ECMA-262 5th Edition (and JavaScript 1.8.5) has ways to do it through the Object.defineProperty and Object.defineProperties methods, by setting the enumerable field of the property to false. That is available in Chrome 5, Safari 5, Firefox 4 and Internet Explorer 9 or any recent server side implementation that uses V8 (like Node.js).

like image 113
Poetro Avatar answered Oct 06 '22 15:10

Poetro