Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prototyping Object in Javascript breaks jQuery?

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?

like image 994
Ben Lesh Avatar asked Dec 01 '09 16:12

Ben Lesh


People also ask

What is jQuery prototype object?

It is simply an object from which other objects can inherit properties. The snippet you have posted simply assigns an object with some properties (such as init ) to the prototype of jQuery , and aliases jQuery.prototype to jQuery.fn because fn is shorter and quicker to type.

What is prototype object in JavaScript?

Every object in JavaScript has a built-in property, which is called its prototype. The prototype is itself an object, so the prototype will have its own prototype, making what's called a prototype chain. The chain ends when we reach a prototype that has null for its own prototype.

Is __ proto __ deprecated?

__proto__ is considered outdated and somewhat deprecated (moved to the so-called “Annex B” of the JavaScript standard, meant for browsers only). The modern methods to get/set a prototype are: Object.

What is the benefit of prototype in JavaScript?

Prototypes allow you to easily define methods to all instances of a particular object. The beauty is that the method is applied to the prototype, so it is only stored in the memory once, but every instance of the object has access to it.


1 Answers

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?

like image 60
nicholas Avatar answered Sep 29 '22 20:09

nicholas