DEV Community

Discussion on: Emulating "Private" Variables in JavaScript with Closures and Factory Functions

Collapse
 
anodynos profile image
Angelos Pikoulas • Edited

Has anyone tried something as naive as this?

The 101 smoke test worked, it seems like _flees are gonna be garbage collected, what could go wrong? You can also attach getters and setters and improve it quite more, make it readonly or writeonly, etc.

class Dog {
  constructor() {
    let _flees = 0;
    this.getFlees = () => _flees;
    this.setFlees = (f) => {_flees = f};
  }
}

const a = new Dog;
const b = new Dog;

a.setFlees(1);
b.setFlees(2);
console.log(a.getFlees());
console.log(b.getFlees());

a.setFlees(11);
b.setFlees(22);
console.log(a.getFlees());
console.log(b.getFlees());
// output 1 2 11 22
Enter fullscreen mode Exit fullscreen mode

The obvious side effect of this simplicity is of that _flees won't be able to be accessed by other methods at all, they all have to use the accessor methods.

So they are super-private.

But is this a wrong thing necessarily? I'm only entertaining the idea, but unless one uses it in practice, one can't know really...

Any thoughts?

Collapse
 
somedood profile image
Basti Ortiz

Honestly, I doubt that anyone has the time to add this level of complexity just for privacy and encapsulation in JavaScript. I wrote this post to inform people that it is indeed possible, albeit rather impractical. Most of us would just prefer using the _ naming convention to denote member privacy.

I wouldn't say it's a "wrong thing", per se. It's still a cool party trick and all, but if one hopes to use this in production code, they better hope that the next person maintaining their code knows enough about JavaScript to understand why all the boilerplate code is necessary for member privacy.