DEV Community

Discussion on: How to avoid namespace pollution in Javascript

Collapse
 
peerreynders profile image
peerreynders

I think we can achieve the same result using classes

The entire idea behind the revealing module pattern is to keep the "private" parts truly "private" inside a function closure created via an intermediately invoked function expression (IIFE). JavaScript always had function closures.

OOP with Functions in JavaScript

Private class fields are only part of the Class field declarations for JavaScript and private methods are part of the Private methods and getter/setters for JavaScript classes TC39 proposals which are currently at Stage 3 - which means they may become part of ES2023 if they go to Stage 4 before then.

Babel right now includes @babel/plugin-proposal-class-prope... and @babel/plugin-proposal-private-met... by default in @babel/preset-env

Can I Use: JavaScript classes: Private class fields

Can I Use: JavaScript classes: Private class methods

MDN: Private Class Features

which has the advantage that you can use setters and getters.

In the example given the object returned includes the getName() accessor and the setName() mutator. But perhaps you were referring to the getter and setter object property syntax:

const myModule = (() => {
  let name = 'Ben Cherry';

  return {
    get name() {
      return name;
    },
    set name(value) {
      name = value;
    },
  };
})();

console.log(myModule.name); // "Ben Cherry"
myModule.name = 'Paul Kinlan';
console.log(myModule.name); // "Paul Kinlan"
Enter fullscreen mode Exit fullscreen mode

It just works!