0

Look at the following code:

class Animal() {
  constructor(type, name) {
    this._type = type;
    this._name = name;
  }

  get type() {
    return this._type;
  }

  get name() {
    return this._name;
  }
}

If I were to run:

var Dog = new Animal("Dog", "Rover"); 
console.log(Dog._name);

The console would return the name of my dog without the need to use the `get name() {} that I wrote above. What is the point of getters and setters in Javascript 6 if I can access my object properties directly? Why is the underscore a convention for private properties when it does nothing to privatize them? How can I make my properties private in classes in Javascript using current ecmascript-6 standards?

Edmond Weiss
  • 311
  • 3
  • 10
  • The point of getters / setters is: you don't need to modify your class interface if the internal representation changes. E.g. if you decide that `type` shall be computed from other properties from now on, you can just do that. Setters often require some computation, e.g. to verify if the value is valid before accepting it. Refer to http://2ality.com/2016/01/private-data-classes.html for a complete discussion of private properties and their pros & cons. – le_m Jun 25 '17 at 22:59
  • Please ask a single question per post only. I hope the duplicates answer everything, if not please ask a more specific question. – Bergi Jun 25 '17 at 23:01

0 Answers0