我应该在子 class 中用 super() 调用父 class 方法吗

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

我对 javascript 中的 super() 有疑问。 我应该在子 class 中用 super() 调用父 class 方法 '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();
    }
}

哪一个是正确的,有什么不同。

没有必要在 Watermelon 中包含 stringy,除非您想更改行为。如果您不这样做,Watermelon 个实例将继承 Melon 版本。 Watermelon 的两个版本 非常接近 相同,并且在任一版本的实例上调用 stringy 将创建和 return 相同的字符串。如果 stringy 使用了参数,你被覆盖的参数需要确保传递它接收到的所有参数,但是 stringy 不使用任何参数,所以...


(为了完整起见:唯一的 细微 区别是在 Watermelon 的第二个版本中,有一个 Watermelon.prototype.stringy功能,而在您的第一个版本中没有。没有也没关系,因为 Watermelon.prototype 继承自 Melon.prototype,后者具有 stringy。)