How do getters relate to privacy?

Question

How do getters relate to privacy?

Answer

Getters can be seen as a support for our privately set properties (using _ in front to let other developers know that its value should not be directly modified). A getter provides the binding between an object’s property and a function to indirectly retrieve the properties value. This way we can add one more layer of protection to that property, for example:

const robot = {
  _model: '1E78V2',
  get model () {
    if(this._model){
      return this._model;
    } else {
      return 'This is not a bot';
    }
  }
}

// in this case we have a getter that returns only the value of _model
// if we console log it:

console.log(robot.model);  // it will give us 1E78V2

//if we decide to change the value:

robot.model = "y43h3"; 

// it will not recognize the changes and the getter will return the set value from robot._model:

console.log(robot.model); // 1E78V2

As you can see a getter only allows retrieval of the value without directly calling the property of the object.

11 Likes

The private variables are not actually private, just given the special bindings mentioned above. They are still publicly accessible. For all instances when the variable is polled, it should go through the getter or setter as a safety precaution.

9 Likes

If privacy is so important in order to avoid unexpected behavior, why doesn’t JavaScript have built in privacy mechanisms like other languages?

1 Like

Privacy is not that important or it would have been addressed, one supposes. Obscuring the backing variable is about as private as it gets. Controlling access to the aliased property has its good points, but I’m not well enough informed to list them.

We still need to keep in mind that ES is prototypal and not class based. ES6 changed a lot to bring the language more in line with other lower level languages but will likely never go the full route like Node.js did, but again, this is stuff that’s over my head.

3 Likes