gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 00:28:57 25 4
gpt4 key购买 nike

我有一个关于 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();
}
}

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

最佳答案

除非您想更改行为,否则无需在 Watermelon 中包含 stringy。如果您不这样做,Watermelon 实例将继承 Melon 版本。您的 Watermelon 的两个版本非常相同,并且在任一版本的实例上调用 stringy 将创建并返回相同的字符串。如果 stringy 使用参数,则覆盖的参数需要确保传递它收到的所有参数,但 stringy 不使用任何参数,因此...

<小时/>

(只是为了完整起见:唯一的细微区别是在您的Watermelon的第二个版本中,有一个Watermelon.prototype.stringy 函数,而在您的第一个版本中没有。没有也没关系,因为 Watermelon.prototype 继承自 Melon.prototype,它具有 字符串。)

关于javascript - 我应该在子类中使用 super() 调用父类方法吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58736833/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com