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.