我应该在子类中使用super()调用父类方法

问题描述 投票:0回答:1

我在javascript中有关于super()的问题。我应该在子类中使用super()调用父类方法'stringy()'还是这样使用它:

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';
    }
}

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();
    }
}

哪个是正确的,和有什么区别。

javascript oop inheritance prototype super
1个回答
0
投票

除非您要更改行为,否则无需在stringy中包含Watermelon。如果您不这样做,Watermelon实例将继承Melon版本。

© www.soinside.com 2019 - 2024. All rights reserved.