39

I have added a simple .js file to my page that has some pretty mundane common-task sort of functions added to the Object and Array prototypes.

Through trial and error, I've figured out that adding any function to Object.prototype, no matter it's name or what it does causes Javascript errors in jQuery:

The culprit?

Object.prototype.foo = function() {
    /*do nothing and break jQuery*/
};

The error I'm getting line 1056 of jquery-1.3.2.js, in the attr:function { } declaration:

/*Object doesn't support this property or method*/
name = name.replace(/-([a-z])/ig, function(all, letter) {
            return letter.toUpperCase();
        });

Apparently G.replace is undefined.

While it's obvious that there's something I'm just not wrapping my head around with prototyping, I'm failing miserably to figure out what it is.

To be clear, I'm not looking for a workaround, I have that handled... what I'm looking for is an answer to Why?. Why does adding a function to Object.prototype break this bit of code?

2
  • 3
    You might get a more meaningful error if you switch over to the full jquery file (non-minified). That way you'll be able to see more clearly what code is having problems. Dec 1, 2009 at 16:53
  • @CrescentFresh's link is outdated. Update: bugs.jquery.com/ticket/2721 Aug 19, 2017 at 10:41

5 Answers 5

47

If it's simply a case of messing up for...in loops, can't you use Object.defineProperty to add your fn without making it enumerable?

So:

Object.defineProperty(Object.prototype, "foo", { 
    value: function() {
        // do stuff
    },
    enumerable : false
});

Seems to work for me. Would this still be considered bad form?

11
  • 1
    I don't know... It would be nice to know if it is bad form, but this is working great for me. Aug 5, 2011 at 23:59
  • 2
    You could, but for..in loops were designed to enumerate prototype extensions. That's how you explore the prototype chain. It doesn't break for..in loops it breaks buggy code that blindy assumes the iterated values will always be of a certain type whereas, because the Object.prototype chain can include functions, the code between the curly brackets can throw an exception when they expect only scalars and objects. Feb 2, 2012 at 19:22
  • 1
    @NoOne I don't think extending the Object prototype is any different than any other prototype. It just has to be done responsibly. The open-source nature of the web, with all the frameworks and plug-ins and tools available, means your project is likely more third-party code than your own. A core tenant of JavaScript is to not modify anything you don't own. If you just extend Object without thinking, you might break something that expects it to behave a certain way.
    – nicholas
    Jun 18, 2015 at 19:36
  • 1
    @NoOne You application is probably going to look something like: Core Javascript (owned by the browser) -> toolkits (like jquery, underscore, etc.) -> framework (backbone, angular, react, etc) -> your application code. Each layer relies on the layers before it behaving a certain way. Reaching backwards and changing the way core data types work is always going to be a problem, in any language.
    – nicholas
    Jun 19, 2015 at 20:26
  • 1
    @NoOne There are plenty of ways you can get the functionality you want in just your application code. You can use libraries like underscore.string, use Object.create(), mixins or factory methods to build functionality into your objects. A good book that covers a lot of techniques for this is JavaScript Patterns (amazon.com/JavaScript-Patterns-Stoyan-Stefanov/dp/0596806752).
    – nicholas
    Jun 19, 2015 at 20:26
20

You should never extend Object.prototype. It does far more than break jQuery; it completely breaks the "object-as-hashtables" feature of Javascript. Don't do it.

You can ask John Resig, and he'll tell you the same thing.

8
  • 21
    Extending Object.prototype is fine. The caveat is to use hasOwnProperty in for..in loops. It's supported in every major browser including Safari since 2.0. It's just laziness that jQuery does not do it in its for..in loops. The performance impact is negligable, and Resig knows this: osdir.com/ml/jquery-dev/2009-02/msg00543.html Just my opinion however. Dec 1, 2009 at 17:28
  • 3
    @Crescent It's much deeper than that. Sure you can work around the problem with for...in loops like that, but having object-as-hashtables in Javascript does lots of other things. For example, toString, valueOf and others are not enumerated. This does have an impact. Also, when you are the lead dev of a library used by tons of people, you can't blame his decision on laziness. I think a better word would be cautious. Dec 1, 2009 at 18:04
  • 3
    @JoshStodola - actually it wasn't laziness it was ignorance (most people didn't know to use hasOwnProperty...) in the early days of jQuery Resig simply didn't know to do so. Soon after realizing the flaw he had always accepted the fix as a needed future implement but alas it never made it into the core. Feb 2, 2012 at 19:15
  • 1
    @CrescentFresh THANK YOU SOOOO MUCH!!! I've been looking for that post for months now! (I'm the author of that post/code diff and the one who worked with Resig to get the bug fixed in jQuery.) I thought it was lost to the ether forever. As an update, I'm sad to report that a few months ago Resig officially closed the ticket as won't fix. The flaw was too pervasive in UI libs and the bad coding practice is too prevalent in the community. It's why I don't use jQuery anymore :( but Sizzle is compatible with Object.prototype extensions and that's my favorite part of jQuery really. Feb 2, 2012 at 19:20
  • 4
    IMHO this answer is now incorrect, and out-of-date. In ES5 you can extend Object.prototype safely using Object.defineProperty with the default settings that create a non-enumerable property.
    – Alnitak
    Jan 9, 2017 at 0:43
4

I agree, adding something to Object.prototype demands caution and should be avoided. Look for other solutions such as:

Adding it to Object and then accessing it with a call or apply, as needed. For example:

Object.foo = function () { return this.whatever()}

Then call that on an object by:

Object.foo.call(Objname);  // this invokes the function as though it were a
                           // method of Objname.  That is, its like Objname.foo()

For fun, you can add the following (yes, I know its a bit dangerous...):

Function.using = Function.call; // syntactic sugar

Now you can write Object.foo.using(Objname) and it reads like a sentance.

But as a rule, stay away from altering any of the big prototypes.

1
  • Downvoting, as this does not explain why extending the object prototype is problematic (which is the question) plus the suggested solution is a somewhat hacky (you can't call arbitraryObject.foo(), for example, which is the main thing that the OP is trying to achieve here).
    – HappyDog
    Apr 1, 2022 at 21:11
2

I banged my head around this problem as I wished to implement "real" object orientation in all of my objects, like this:

interface Object
{
    GetType: () => string;
    ToString: () => string;
    GetHashcode: () => number;
    Equals: (obj: any) => boolean;
}

Since Object.prototype breaks JQuery, I defaulted to the abovementioned solution to make use of defineProperty but that does not take any arguments.

The good news is that you can hack into defineProperty and actually accept parameters. Here is my implementation:

Object.defineProperty(Object.prototype, "Equals",
    {
        value: function (obj: any)
        {
            return obj == null && this == null
                    ? true
                    : obj != null && this == null
                        ? false
                        : obj == null && this != null
                            ? false
                            : this.GetHashcode() == obj.GetHashcode();
        },
        enumerable: false
    });

This works and does not clash with JQuery.

1
  • This seems to be the best answer. Does not seem to clash with Google Maps API either.
    – vaid
    Jan 9, 2019 at 11:19
-1

I doubt adding a function to Object.prototype breaks jQuery directly. Just make sure each for..in loop you have throughout your site is wrapped in a hasOwnProperty check, since you've add the function globally and the result of iterating over it can be unpredictable:

Object.prototype.foo = function() {};    
var myObject = {m1: "one", m2: "two" };

for(var i in myObject) { if(myObject.hasOwnProperty(i)) {
   // Do stuff... but not to Object.prototype.foo
}}
4
  • Well if I comment out the Object.prototype.foo declaration, everything works just fine. Also, at the point it's breaking, it hasn't even reached any of my code beyond that foo declaration.
    – Ben Lesh
    Dec 1, 2009 at 17:04
  • 1
    You're right it does not break jQuery directly, it breaks Javascript! Dec 1, 2009 at 17:16
  • Depends on how you look at it. Ideally you should be able to extend Object with no problem, but in reality, yeah it's a bad idea and there's rarely a good reason for it. Crockford sees enumerating over functions added to the prototype as a "mistake in the language" and so the best practice is to be defensive and ALWAYS add hasOwnProperty to for..in loops. It sucks, but I do it religiously ;)
    – jshalvi
    Dec 1, 2009 at 18:25
  • 3
    Yes, it breaks jQuery, jQuery will iterate over your Object.prototype extension but assume that it's not a function. When that function appears in the iteration it throws an exception. It doesn't break JavaScript, it's very integral to the design of JavaScript. @jshalvi - you could always create an interator function like jQuery's $.each and just write it once. Crockford has a few misinterpretations about the language but it's not really his fault he pioneered the wild western JavaScript frontier and he only got a few things wrong in the journey. :D Feb 2, 2012 at 19:28

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.