Javascript Getters and Setters

Getters and setters make sense in java, and I just learned that there is an equivalent pattern in javascript:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
> 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:

1
2
3
4
5
6
> 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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
> 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.

Resources

The principles of object-oriented javascript