Search code examples
javascriptreactjsprototypees6-modules

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 want to find any good way to add prototypes to global scope.

arrayHelpers.js

Array.prototype.unique = () => {
   //... some code
};

SomeComponent.js

export default const SomeComponent = () => {
   const someArray = ["foo", "bar", "foo"];
   const someArrayThatHasOnlyUniqueItems = someArray.unique(); // ["foo", bar"]

   // ... more code 
};

I don't want to use classic functions like unique(array), because prototypes are much cleaner and easier to use.

Also, importing any file into every single component is not the best way to do that.


Solution

  • 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):

    class MyArray extends Array {
      function unique() {
        //...
      }
    }
    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 = new Symbol('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.