1

I'm trying to assign a function to Object.prototype.equals similar to what's done in Object comparison in JavaScript. The function works perfectly, but whenever I have jQuery about, I get errors like:

name.replace is not a function

referring to line 6490 in jquery-1.6.1.js.

Does anyone know why this could be happening?

Community
  • 1
  • 1
josef.van.niekerk
  • 11,941
  • 20
  • 97
  • 157

1 Answers1

5

Don't monkey patch Object.prototype.

Object.prototype.replace = "lol";

for (var i in { "bar": 42 }) {
  alert(i);
}
// "bar"
// "replace" :(

Basically for ... in loops iterate over all properties in an object including ones defined on the prototype. This is why it's really bad practice to extend or change Object.prototype.

Some people also go as far as "Don't monkey patch Array, String, Function, ...".

You should never mess with the Object.prototype. The rest of the native prototypes are a style choice.

Define your function on Object.

Object.replace = function() { ... };

var o = Object.replace(p);

ES5:

With ecmascript 5 you can set properties as non-enumerable

Object.defineProperty(Object.prototype, "replace", {
  value: function() { }
});
Raynos
  • 166,823
  • 56
  • 351
  • 396