views:

89

answers:

3

Adding methods to native JavaScript objects like Object, Function, Array, String, etc considered as bad practice.

But I could not understand why?

Can some body shed light on this?

Thanks in advance.

+6  A: 

Because you might happen to use a library that defined a function with the same name, but working another way.

By overriding it, you break the other's library's behaviour, and then you scratch your head in debug mode.

Edit

If you really want to add a method with a very unpleasant name like prependMyCompanyName(...) to the String prototype, I think it's pretty much risk-free from an overriding point of view. But I hope for you that you won't have to type it too often...

Best way to do it is still, in my humble opinion, to define for example, a MyCompanyUtils object (you can find a shortcut like $Utils), and make it have a prepend(str,...) method.

subtenante
Say if I add a function prependMyCompanyUSP() in String object, how it is going to affect other library. Sorry, if I asked a dump question. A example may a clear my rocky head.
rajakvk
If you use a generic name you are likely to end up with the function replacing (or being replaced by) a function from library or later version of the spec.eg. String.prototype.trim = function () { ... }that removes extra formatting would result in incorrect behaviour in a new ES implementation (in ES5 String.prototype.trim exists).By doing String.prototype.myCompanyNameTrim = function....You are much less likely to get a name collision.
olliej
@olliej perfect. I got it now. thanks. shy!!
rajakvk
+1  A: 

The two big reasons in my opinion are that:

  1. It makes your code harder to read. You write code once and read it many number of times more. If your code eventually falls into the hands of another person he may not immediately know that all of your Objects have a .to_whatever method.

  2. It causes the possibility of namespace conflicts. If you try to put your library which overrides Object.prototype into another library, it may cause issues with other people doing the same thing.

camwest
A: 

There is also the effect that augmenting the Object prototype has on for...in loops to consider:

Object.prototype.foo = 1;

var obj = {
  bar: 2
};

for (var i in obj) {
  window.alert(i);
}

// Alerts both "foo" and "bar"
Tim Down