Working with JavaScript Subclasses

Working with subclasses

Like most of the new additions, there's a lot less setup code and it's a lot cleaner syntax to create a subclass using class, super, and extends.

Just remember that, under the hood, the same connections are made between functions and prototypes.

supermust be called beforethis

In a subclass constructor function, beforethiscan be used, a call to the super class must be made.

class Apple {}
class GrannySmith extends Apple {
  constructor(tartnessLevel, energy) {
    this.tartnessLevel = tartnessLevel; // `this` before `super` will throw an error!
    super(energy); 
  }
}

QUESTION 1 OF 2

Take a look at the following code:

class Toy {}
class Dragon extends Toy {}
const dragon1 = new Dragon();

Given the code above, is the following statement true or false?

dragon1 instanceof Toy;
  • true

  • false

SUBMIT: The dragon1 variable is an object created by the Dragon class, and since the Dragon class extends the Toy class, dragon1 is also considered an instance of Toy.

QUESTION 2 OF 2

Let's say that aToyclass exists and that aDragonclass extends theToyclass.

What is the correct way to create aToyobject from inside theDragonclass'sconstructormethod?

  • super();

  • super.call(this);

  • parent();

  • Toy();

SUBMIT: Option 1 is the correct way to call the super class from within the subclass's constructor function.

Quiz: Building Classes and Subclasses

/*
 * Programming Quiz: Building Classes and Subclasses (2-3)
 */

class Vehicle {
    constructor(color = 'blue', wheels = 4, horn = 'beep beep') {
        this.color = color;
        this.wheels = wheels;
        this.horn = horn;
    }

    honkHorn() {
        console.log(this.horn);
    }
}

// your code goes here

class Bicycle extends Vehicle {
    constructor(color, wheels = 2, horn = 'honk honk') {
        super(color); // Only importing the value (of color) from Vehicle
        //this.color = color;
        this.wheels = wheels;
        this.horn = horn;
    }
}


const myVehicle = new Vehicle();
myVehicle.honkHorn(); // beep beep
const myBike = new Bicycle();
myBike.honkHorn(); // honk honk

results matching ""

    No results matching ""