Using setters to encapsulate values
In the previous recipe, we saw how to prevent values from being written. Sometimes however, we don't want to prevent a property from being written to. Rather, we want to control how it is written to. In this recipe, we'll see how to use set to control the writing of a property.
Getting ready
This recipe assumes you already have a workspace that allows you to create and run ES modules in your browser. If you don't, please see the first two chapters.
How to do it...
- Open your command-line application and navigate to your workspace.
- Create a new folder named
07-06-setters-encapsulate. - Copy or create an
index.htmlthat loads and runs amainfunction frommain.js. - Create a
main.jsfile with aRocketclass that writes a _secretNameproperty upon construction:
class Rocket {
constructor(name) {
this._secretName = name;
}
} - Add a getter and setter for a
nameproperty and only update it if thenewValueis a string:
class Rocket {
// ...
get name() {...