Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.
Hi all, please see this major site announcement: https://www.boards.ie/discussion/2058427594/boards-ie-2026

Avoiding JS Global pollution with prototyping

  • 26-06-2017 02:43PM
    #1
    Registered Users, Registered Users 2 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, Registered Users 2 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