K
K
Kirill Popolov2014-10-10 10:00:21
JavaScript
Kirill Popolov, 2014-10-10 10:00:21

How to properly extend the functionality of standard objects in js?

I would like to add several methods for working with strings and arrays. I can't figure out how best to do:
* Through the prototype (Array.prototype). The easiest way, but it seems to me that this can cause conflicts if used in someone else's code.
* Through a child object (makes it more difficult because you need to create an instance of a new object each time)
* Through a simple function
Perhaps there are other ways? What are the pros and cons of these methods?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
N
Nazar Mokrinsky, 2014-10-10
@nazarpc

The third incomprehensible, the first and second are quite options, if you ignore that the extension of standard objects is not recommended.
Conflicts may indeed arise with the first, plus the methods will be even where you do not use them. With the correct addition and confidence that there will be no conflicts, you can use it.
In the second, it is easier because it is used only where necessary, does not interfere with anyone, but the convenience drops significantly.

D
Denis Pushkarev, 2014-10-10
@rock

Well, what other options could there be? :)
According to the first - if you use it, then you need to make sure that the given method is not in the standard / at least one implementation . If their analogues are present there - can it be better to implement them? Extend prototypes only using defineProperty with enumerable: false so as not to break for-in. Well, do not use any other libraries that extend build-in objects, except for polyfills.
Not satisfied - then the second or third. They are easily combined, see, for example, how it is implemented in undescore.js

R
Rrooom, 2014-10-10
@Rrooom

A better third way is the undescore and lodash approach. Convenient, beautiful, cannot break external libraries.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question