Javascript Class Inheritance with Derived Classes

Introduction

ECMAScript 6 classes uses extends keyword to specify class from which the class should inherit.

The prototypes are automatically adjusted.

You can access the base class constructor by calling the super() method.

class Rectangle {//from  w w w.  ja  v a 2 s. c  o m
    constructor(length, width) {
        this.length = length;
        this.width = width;
    }

    getArea() {
        return this.length * this.width;
    }
}

class Square extends Rectangle {
    constructor(length) {

        // same as Rectangle.call(this, length, length)
        super(length, length);
    }
}

var square = new Square(3);

console.log(square.getArea());              // 9
console.log(square instanceof Square);      // true
console.log(square instanceof Rectangle);   // true

Square class inherits from Rectangle using the extends keyword.

The Square constructor uses super() to call the Rectangle constructor with the specified arguments.

Classes that inherit from other classes are referred to as *derived classes*.

class Square extends Rectangle {
    // no constructor
}

// Is equivalent to

class Square extends Rectangle {
    constructor(...args) {/*w w  w .  j  av a2  s. co m*/
        super(...args);
    }
}



PreviousNext

Related