How to do it...

  1. Open your command line application and navigate to your workspace.
  2. Create a new folder named 08-04-checking-with-instanceof.
  3. Copy or create an index.html that loads and runs a main function from main.js.
  4. Create two objects rocketMap and inactiveRocketMap:
// main.js 
let rocketMap = {};  
let inactiveRocketMap = {}; 
  1. Define a new class named Rocket. Add a constructor. Use the name to assign the instance to the rocketMap and define a simple print method:
// main.js 
class Rocket { 
  constructor(name) { 
    this.name = name; 
    rocketMap[name] = this; 
     } 
  print() { 
    console.log(this.name + ' is a rocket'); 
  } 
}  
  1. Add a static find method that retrieves an instance from the rocketMap:
// main.js 
class Rocket { 
  static find (name) { 
    return rocketMap[name]; 
  } 
} 
  1. Create a class named InactiveRocket that extends the Rocket class and assigns an additional lastFlow property in the constructor. Use the name to assign the instance to the inactiveRocketMap and override the print method to include the new property:
// main.js 
class InactiveRocket extends Rocket { 
 constructor(name, lastFlown) { 
    super(name); 
    this.lastFlown = lastFlown; 
    inactiveRocketMap[name] = this; 
  } 
 
  print() { 
    console.log(this.name + ' is an inactive rocket'); 
    console.log(`${this.name} was last flown: 
${this.lastFlown}`); } }
  1. Add a static find method that retrieves an instance from the rocketMap:
// main.js 
class InactiveRocket { 
  static find (name) { 
    return inactiveRocketMap[name]; 
  } 
} 
  1. Create a main function that creates instances of both classes and try to retrieve the instances from the maps:
// main.js 
export function main() { 
  const saturnV = new InactiveRocket('Saturn V'); 
  const falconHeavy = new Rocket('Falcon Heavy'); 
 
  // print rocket for saturn V and falcon heavy 
  console.log('All Rockets:'); 
  Rocket.find('Saturn V').print(); 
  Rocket.find('Falcon Heavy').print(); 
  
  // print inactive entry for saturn v and attempt falcon 
  console.log('Inactive Rockets:'); 
  InactiveRocket.find('Saturn V').print(); 
  // throws an error 
  InactiveRocket.find('Falcon Heavy').print(); 
} 
  1. Start your Python web server and open the following link in your browser:
    http://localhost:8000/.
  2. You should see output like the following:
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.216.216.240