Javascript Class Shadowing Class Methods

Introduction

The methods on derived classes shadow methods of the same name on the base class.

For instance, you can add getArea() to Square to redefine that functionality:

class Rectangle {//from  w  w w.j  av  a2  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) {
        super(length, length);
    }

    // override and shadow Rectangle.prototype.getArea()
    getArea() {
        return this.length * this.length;
    }
}

You can always decide to call the base class version of the method by using the super.getArea() method, like this:

class Square extends Rectangle {
    constructor(length) {//  w  ww  .  ja v  a 2  s.  c  o m
        super(length, length);
    }

    // override, shadow, and call Rectangle.prototype.getArea()
    getArea() {
        return super.getArea();
    }
}



PreviousNext

Related