How to do it...

  1. Open your command-line application and navigate to your workspace.
  2. Create a new folder named 07-06-setters-encapsulate.
  3. Copy or create an index.html that loads and runs a main function from main.js.
  4. Create a main.js file with a Rocket class that writes a ­_secretName property upon construction:
class Rocket { 
  constructor(name) { 
    this._secretName = name; 
  }  
} 
  1. Add a getter and setter for a name property and only update it if the newValue is a string:
class Rocket { 
  // ... 
  get name() {    return this._secretName;  }  set name(newValue) {    if (typeof newValue === 'string') {      this._secretName = newValue;    } else {      console.error('Invalid name: ' + newValue)    } }
  1. Create a main function that tries to set the name property to different ...

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.