How to do it...

  1. Open your command-line application and navigate to your workspace.
  2. Create a new folder named 07-05-getters-read-only.
  3. Copy or create an index.html that loads and runs a main function from main.js.
  4. Create a main.js file with the Rocket class that defines a read only property:
class Rocket { 
  constructor(name) { 
    this.name = name; 
  } 
 
  get readOnlyValue() { 
    return 'Cant' touch this.'; 
  } 
} 
  1. Create a main function that creates an instance of the Rocket class. Read from the writable and read-only properties, then try to write to them:
export function main() { const saturnV = new Rocket('Saturn V'); console.log(saturnV.name); saturnV.name = 'Saturn Five'; console.log(saturnV.name); console.log(saturnV.readOnlyValue); // throws error ...

Get ECMAScript Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.