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.
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.
- Open your command-line application and navigate to your workspace.
- Create a new folder named
07-06-setters-encapsulate
. - Copy or create an
index.html
that loads and runs amain
function frommain.js
. - Create a
main.js
file with aRocket
class that writes a _secretName
property upon construction:
class Rocket { constructor(name) { this._secretName = name; } }
- Add a getter and setter for a
name
property and only update it if thenewValue
is a string:
class Rocket {
// ...
get name() {...