Is it recommended to use prototype on native objects?

4

I think the idea of having my own methods imported into the javascript native objects is very good.

As 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 is this practice recommended?

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

    
asked by anonymous 23.02.2015 / 16:42

1 answer

3

Like all programming style questions, there is not a 100% sure answer in this case but I'm not much of a fan of adding methods to native objects.

  • The prototype of native methods has a global scope. If two modules in your project attempt to override 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, a lot of people had a headache when browsers started to implement forEach into vectors because the native implementation is subtly different from the implementation that the libraries were adding.

  • Methods you insert into prototype may appear when you iterate on the object with a for in loop. This may break code that did not expect the presence of these methods 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 that the cute notation of x.metodo() instead of LIB.metodo(x) does not make up for breaking the principle of single responsibility.

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

    
23.02.2015 / 17:25