Search code examples
javascriptoopinheritanceprototypesuper

Should i call the parent class method with super() in the child class


I have a question about super() in javascript. Should i call the parent class method 'stringy()' with super() in the child class or i can use it like this:

function solve() {
class Melon {
    constructor(weight, melonSort) {
        if (new.target === Melon) {
            throw new Error('Abstract class cannot be instantiated directly.')
        }
        this.weight = weight;
        this.melonSort = melonSort;
        this._elementIndex = weight * Number(melonSort.length);

    }
    stringy() {
        return `Element: ${this.element}\nSort: ${this.melonSort}\nElement Index: ${this._elementIndex}`
    }
}

class Watermelon extends Melon {
    constructor(weight, melonSort) {
        super(weight, melonSort);
        this.element = 'Water';
    }
}

or

function solve() {
class Melon {
    constructor(weight, melonSort) {
        if (new.target === Melon) {
            throw new Error('Abstract class cannot be instantiated directly.')
        }
        this.weight = weight;
        this.melonSort = melonSort;
        this._elementIndex = weight * Number(melonSort.length);

    }
    stringy() {
        return `Element: ${this.element}\nSort: ${this.melonSort}\nElement Index: ${this._elementIndex}`
    }
}

class Watermelon extends Melon {
    constructor(weight, melonSort) {
        super(weight, melonSort);
        this.element = 'Water';
    }

    stringy(){
        return super.stringy();
    }
}

which one is correct and what is the difference.


Solution

  • There's no need to include stringy in Watermelon unless you want to change the behavior. Watermelon instances will inherit the Melon version if you don't. Your two versions of Watermelon are very nearly identical, and calls to stringy on instances of either version will create and return the same string. If stringy used arguments, your overwritten one would need to be sure to pass all arguments it received along, but stringy doesn't use any, so...


    (Just for completeness: The only slight difference is that in your second version of Watermelon, there is a Watermelon.prototype.stringy function, whereas in your first version there isn't. It's fine that there isn't, because Watermelon.prototype inherits from Melon.prototype, which has stringy.)