2

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.

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
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.
1

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.

Comments

1

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"

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.