PROGRAMMING

  MINTE9
REMEMBERS




Last update:   27-01-2022

Extend

Inheritance is a way for one class to extend another class.
 
/**
 * Extend another class
 */

 class Animal
 {
    constructor(name) {
        this.speed = 0;
        this.name = name;
    }

    run(speed) {
        this.speed = speed;
        console.log(`${this.name} runs with speed ${this.speed}`);
    }

    stop() {
        this.speed = 0;
        console.log(`${this.name} stops`);
    }
}

class Rabbit extends Animal
{
    hide() {
        super.stop();
        console.log(`${this.name} hides!`);
    }
}

let rabbit = new Rabbit("My Rabbit");

rabbit.run(100); 
    // My Rabbit runs with speed 100
rabbit.stop(); 
    // My Rabbit stops
rabbit.run(50); 
    // My Rabbit runs with speed 50
rabbit.hide(); 
    // My Rabbit stops
    // My Rabbit hides!

Super

Constructors in inheriting classes must call super(), and do it before using this.
 
/**
 * If a class extends another class and has no constructor,
 * then a default constructor is generated:
 * 
 *  constructor(...args) {
 *      super(...args);
 *  }
 * 
 * We get an error when trying to add a custom constructor without
 * calling super() first
 */

class Animal 
{
    constructor(name) {
        this.speed = 0;
        this.name = name;
    }
}

class Rabbit extends Animal
{
    constructor(name) {
        super(name); // Look Here
        this.name = name.toUpperCase();
    }
}

let rabbit = new Rabbit("My Rabbit");
console.log(rabbit.name); // MY RABBIT

Questions     github Classes


        A B C D E F
🔔
1/1