Is it recommended to use prototype on native objects?

Asked

Viewed 124 times

4

I think it’s great to have my own methods imported into the Javascript native objects.

For example:

String.prototype.hello = function(){
     return this.toString() + ' hello';
}

'Say '.hello() // say hello

Number.prototype.add = function(){
   return this + 1;
}

(1).add() // 2

But this practice is recommended?

Is there any downside to doing this? Or would it be a better practice to create my own object?

  • 1

    Duplicate? http://answall.com/questions/48070/addir-propriedades-ao-element-node Even if it is not, I believe that the same reasoning as my answer applies.

  • Very useful, @bfavaretto.

1 answer

3


Like all programming style questions, there is no 100% right answer in this case but I’m not a big fan of adding methods to native objects.

  • The native methods prototype has a global scope. If two modules in your project attempt to overwrite the same method there may be conflict.

  • It may be that a future version of your browser will implement some of the methods you have overwritten. For example, many people had headaches when browsers started implementing the forEach in vectors because the native implementation is subtly different from the implementation that libraries used.

  • Methods entered by you into the prototype may appear when you iterate on the object with a loop for in. This can break code that did not expect these methods to be present and is particularly inconvenient in the case of Object.prototype, since it is common to use for-in hash tables.

  • The advantage of implementing something as a method rather than as a function in a separate library is that dispatching is dynamic and we can take advantage of this if we implement a method with the same name in more than one class. However, in many cases (like your add and hello examples) the methods are not generic and only make sense in a single class. In this case I think the cute notation of x.metodo() instead of LIB.metodo(x) it does not pay to break the principle of single liability.

The exception in my opinion is when we edit the prototype to add methods that exist in recent versions of browsers but do not exist in older versions. This serves to increase the compatibility of your program with old browsers and does not go against the first two items on my list because we are only inserting methods that we know will never cause conflict. That said, I suggest using existing implementations like the project es5 Shim instead of reimplementing things in hand. Some details are very subtle.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.