3

I was reading about data privacy in JavaScript and how to achieve that in ES6 Class. I notice this

class Person {
    constructor(name) {
        let _name = name
        this.setName = function(name) { _name = name; }
        this.getName = function() { return _name; }
    }
}

then we cannot access _name like

const p1 = new Person('bob');
p1._name = 'John';

because _name is not part of the properties of the object. It seems like it can achieve data privacy. But I was wondering if this is a good practice.

Joji
  • 2,372
  • 1
  • 12
  • 31

1 Answers1

2

A large majority of developers are aware of a leading underscore being a private variable and not for general API usage. So it being visible or not shouldn't really matter. Where as having getters and setters for every single property can really be too much boilerplate and frankly a waste of time.

Furthermore, this.setName and this.getName are not attached to the prototype chain which removes the ability for pretty much any optimization to occur - such as being able to reuse class methods between multiple instances.

If you want true privacy, use a factory function rather than a class.

And in response to your question, no it generally isn't good practice to write out classes that way.

Reda
  • 1,291
  • 9
  • 12