【发布时间】:2020-03-03 07:57:36
【问题描述】:
我有一个关于 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 学习面向对象的编程。而是选择一种适当支持这种范式的语言。类只是 JavaScript 中的语法糖。
标签: javascript oop inheritance prototype super