Javascript Class Inheritance with extends keyword

Description

Javascript Class Inheritance with extends keyword

"use strict";/*from   www  .  ja v  a2s .  co  m*/

class Person{
    constructor(name, age, weight){
        this.name = name;
        this.age = age;
        this.weight = weight;
    }

    displayName(){
        console.log(this.name);
    }

    displayAge(){
        console.log(this.age);
    }

    displayWeight(){
        console.log(this.weight);
    }
}

class Programmer extends Person{
    constructor(name, age, weight, language){
        super(name, age, weight);
        this.language = language;
    }
    displayLanguage(){
        console.log(this.language);
    }
}

let prawee = new Person('Prawee', 28, 160);
prawee.displayName();
prawee.displayAge();
prawee.displayWeight();

console.log('---------------');
let kob = new Programmer('Kob', 18, 165, 'Javascript');
kob.displayName();
kob.displayAge();
kob.displayWeight();
kob.displayLanguage();

Another example

// ES6//  www.ja  v  a  2s.c o  m
class Car {
    constructor( { title } ) {
        this.title = title;
    }

    drive() {
        return 'vroom';
    }
}

class Toyota extends Car {
    constructor( options ) {
        super(options); // Car.constructor()
        this.color = options.color;
    }

    honk() {
        return 'beep';
    }
}

const toyota = new Toyota( { color : 'red', title : 'Daily driver' } );
console.log( toyota );
console.log( toyota.honk() );
console.log( toyota.drive() );



PreviousNext

Related