Global Prototypes For Big Solutions (javascript/node)
Is there any best practice to write prototypes for classes like Array, Number, etc. for global scope in modular JavaScript? For example I have a create-react-app application and i
Solution 1:
Extending native prototypes is very frowned upon. This is how you break the internet!
You could create a custom Array type by extending the existing one (in which case you'll have to import your custom Array in every file you need to create one):
classMyArrayextendsArray{
functionunique() {
//...
}
}
const someArray = new MyArray("foo", "bar")
You could extend the Symbols prototype of Array (in which case you'll have to import your Symbol in every file you need to use the function):
const unique = newSymbol('unique')
Array.prototype[unique] = () => { ... }
// ...
someArray[unique]()
But probably the best way to do it would be to simply make it a pure standalone function:
function unique(array) {
// ...
}
unique(someArray)
Yes it is boring, like most good code should be.
Yes it isn't as sugary (but if you like sugar, you could always write your own Babel plugin).
Yes you have to import it everywhere (most JS projects have a lot of imports on every file).
Yes this is the way to do it.
Post a Comment for "Global Prototypes For Big Solutions (javascript/node)"