Getters and setters make sense in java, and I just learned that there is an equivalent pattern in javascript:
> var favouriteBook = {
_title: "Catch-22",
get title() {
console.log("Getting title", this._title);
},
set title(value) {
this._title = value;
console.log("Setting title", this._title);
}
}
> favouriteBook.title
Getting title Catch-22
> favouriteBook.title = "Slaughterhouse 5"
Setting title Slaughterhouse 5
> favouriteBook.title
Getting title Slaughterhouse 5
The get
and set
key words are reserved for accessing or mutating a data property (instance variable). Of course, one can get and set data properties directly:
> favouriteBook.title
"Catch-22"
> favouriteBook.title = "Slaughterhouse 5"
> favouriteBook.title
"Slaughterhouse 5"
The advantage of using a getter and setter is that if a setter is defined without a getter, one can change the value of the data property, but can never read it. If a getter is defined without a setter, then the variable can be read but not be changed:
> var favouriteBook = {
_title: "Catch-22",
get title() {
console.log("Getting title", this._title);
}
}
> favouriteBook.title
Getting title Catch-22
> favouriteBook.title = "Slaughterhouse 5"
> favouriteBook.title
Getting title Catch-22
The setter function will fail silently, which makes troubleshooting difficult but ensures that the property remains undisturbed.