Creating new classes using inheritance

Sunday, Aug 9, 2020
JavaScript

If we want to create a new class but also want to reuse some (or all) methods from other classes, we use inheritance.

Using ‘extends’ to get everything from parent and override some

If we want to use all the properties of an existing class with few modifications to one or more methods, we can use extends keyword. In the following example, ‘Moderator’ class is created by extending ‘Member’ class. Moderator inherits everything from Member but overrides its ‘canEdit()’ method.

class Member{
    constructor(name){
        this.name = name;
    }

    createEmail(){
        return `${this.name}@writers.com`;
    }

    canEdit(){
        return false;
    }
}

const member = new Member("eoboy");
console.log(member.createEmail());
// eoboy@writers.com
console.log(member.canEdit());
// false

class Moderator extends Member{
    canEdit(){
        return true;
    }
}

const moderator = new Moderator("krita");
console.log(moderator.createEmail());
// krita@writers.com
console.log(moderator.canEdit());
// true

Using ‘prototype’ inheritence to only inherit some

If our new class needs only a few methods from existing classes, we can use prototypical inheritance to inherit from multiple classes. In the following example, we want to create an ‘Electricbike’ class, which seems like can be done by simply extending ‘Bike’ class but while doing so, we also get its ‘gas’ property and ‘hasGas()’ method which does not make sense for our electric bike. So instead of extending the Bike class, we create a completely independent Electricbike class and inherit ‘isMoving()’ method from Bike using the following format:

<MyClass>.prototype.<prop1> = <OtherClass>.prototype.<prop1>
<MyClass>.prototype.<prop2> = <AnotherClass>.prototype.<prop2>

Note below that the prototype inheritence statements are written outside of the main class definition.

class Bike{
    constructor(name, speed = 0, gas = 10){
        this.name = name;
        this.speed = speed;
        this.gas = gas;
    }

    isMoving(){
        return this.speed > 0;
    }

    hasGas(){
        return this.gas > 0;
    }

}

class Electricbike{
    constructor(name, speed = 0, battery = 10){
        this.name = name;
        this.speed = speed;
        this.battery = battery;
    }

    hasCharge(){
        return this.battery > 0;
    }
}
Electricbike.prototype.isMoving = Bike.prototype.isMoving;

const myBike = new Electricbike("hero", 0, 20);

console.log(myBike);
// Electricbike { name: 'hero', speed: 0, battery: 20 }
console.log(myBike.speed);
// 0
console.log(myBike.isMoving());
// false