We don't always want a property to be writable. In previous recipes, we saw how to create a read-only property on an object. In this recipe, we'll see how to use the get
keyword to do this in the context of a class body.
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-05-getters-read-only
. - Copy or create an
index.html
that loads and runs amain
function frommain.js
. - Create a
main.js
file with theRocket
class that defines a read only property:
class Rocket { constructor(name) { this.name = name; } get readOnlyValue() { return 'Cant' touch this.'; } }
- Create a
main
function that creates an instance of theRocket
class. Read from the writable and read-only properties, then try to write to them...