Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Avoiding JS Global pollution with prototyping

Options
  • 26-06-2017 3:43pm
    #1
    Registered Users Posts: 1,298 ✭✭✭


    What does everyone in here tend to use as an approach to avoiding Global namespace pollutions, e.g. if you're extending the array prototype or string prototype.


Comments

  • Registered Users Posts: 403 ✭✭counterpointaud


    What does everyone in here tend to use as an approach to avoiding Global namespace pollutions, e.g. if you're extending the array prototype or string prototype.

    Something like this? (ES6):
    Object.assign(Array.prototype, {
        unique() {
          return this.filter((value, index, array) => {
            return array.indexOf(value) === index;
          });
        }
    });
    

    or this (if you don't want to actually add them to the prototype)
    class SubArray extends Array {
        constructor(...args) { 
            super(...args); 
        }
        unique() {
          return this.filter((value, index, array) => {
            return array.indexOf(value) === index;
          });
    }
    

    But to be honest I've never felt the need for either. Tend to just use use utility functions.

    EDIT: Just realised I didn't actually really answer your question. The answer is I don't pollute the global namespace because I don't tend to extend base prototypes or add stuff to window/global object. Haven't come across a case where that was necessary. What is the problem you are trying to solve?


Advertisement