Using getters to create read-only properties
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.
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-05-getters-read-only. - Copy or create an
index.htmlthat loads and runs amainfunction frommain.js. - Create a
main.jsfile with theRocketclass that defines a read only property:
class Rocket {
constructor(name) {
this.name = name;
}
get readOnlyValue() {
return 'Cant' touch this.';
}
} - Create a
mainfunction that creates an instance of theRocketclass. Read from the writable and read-only properties, then try to write to them...