【问题标题】:Should i call the parent class method with super() in the child class我应该在子类中用 super() 调用父类方法吗
【发布时间】: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


【解决方案1】:

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


(仅出于完整性考虑:唯一的细微不同之处在于,在您的第二个版本的Watermelon 中,有一个Watermelon.prototype.stringy 函数,而在您的第一个版本中则没有. 没有也没关系,因为Watermelon.prototype 继承自Melon.prototype,后者有stringy。)

【讨论】:

  • ……更明显的区别是覆盖方法无法将参数传递给被覆盖的方法。
  • @Bergi - 被覆盖的不使用任何参数,所以这一点没有实际意义。
猜你喜欢
  • 2014-08-10
  • 1970-01-01
  • 2016-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-09
  • 2011-09-04
相关资源
最近更新 更多