[英]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
将创建并返回相同的字符串。 如果stringy
使用了 arguments,那么您覆盖的需要确保通过它收到的所有 arguments,但stringy
不使用任何,所以...
(为了完整起见:唯一的细微差别是在您的第二个版本的Watermelon
中,有一个Watermelon.prototype.stringy
function,而在您的第一个版本中没有。没有很好,因为Watermelon.prototype
继承自Melon.prototype
,它有stringy
。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.