【问题标题】:How to call a parent class method inside a child class method of the same name?如何在同名的子类方法中调用父类方法?
【发布时间】:2019-04-28 14:47:26
【问题描述】:

我正在尝试使用 ES6 中的类语法创建一个简单的继承结构。我有一个带有方法的父类,比如update(),还有一个也需要update() 方法的子类。我想调用 child.update() 以包含对 parent.update() 的调用,以及包含特定于子类的一些附加功能。

我发现在子类中创建这个方法似乎覆盖了父类中对该方法的引用,这意味着我不能同时调用两者。

这是一个例子:

class Xmover {
    constructor(x, speedX) {
        this.x = x;
        this.speedX = speedX;
    }

    update() {
        this.x += this.speedX;
    }
}

class XYmover extends Xmover {
    constructor(x, y, speedX, speedY) {
        super(x, speedX);
        this.y = y;
        this.speedY = speedY;
    }

    update() {
        this.y += this.speedY;
        // *** I would like this to also update the x position with a call
        //    to Xmover.update() so I don't have to repeat the code ***
    }
}

testXY = new XYmover(0, 0, 10, 10);
console.log(`Start pos: ${textXY.x}, ${testXY.y}`);
testXY.update();
console.log(`End pos: ${textXY.x}, ${testXY.y}`);

这会产生输出:

Start pos: 0, 0
End pos: 0, 10

如您所见,y 位置通过调用XYmover.update() 正确更新,但这个新定义覆盖了对Xmover.update() 的任何调用。如果两个函数都被调用,我们希望看到结束位置10, 10

我见过不使用此类语法的人通过以类似于以下方式创建原始超级函数的副本来解决此问题:

var super_update = this.update;
update() {
    // ... other functionality
    super_update();
}

但是,这对我来说并不理想,而且它也不适用于类语法(除非您在子类构造函数中定义此 super_update,这似乎会产生其他问题子对象的每个实例中 parent.update() 函数的完整副本)。

我是 Javascript 新手,所以我还没有完全理解使用原型的机制 - 也许最好的解决方案以某种方式涉及这些?然而,在我的理解水平上,它们的工作方式类似,因为即使定义了原型函数,创建具有该名称的函数也意味着原型也永远不会被调用。

【问题讨论】:

    标签: javascript class


    【解决方案1】:
     super.update();
    

    那不是super吗?这将在超类中查找update 函数,并使用正确的this 调用它。

    【讨论】:

    • ...我不知道我是怎么错过的,但你是对的。谢谢
    • @HG- 它是 ES6 中未被充分利用的重要新特性之一,因此很多教程/文档没有提及它也就不足为奇了。
    • 这很公平——尽管它似乎与我过去广泛使用的 Java 中的语法几乎完全相同。我好像有点生疏了。感谢您的帮助!
    • 是的,class 语法的添加主要是为了让 JavaScript 对来自其他语言的开发人员更有用,所以它看起来类似于 Java。
    猜你喜欢
    • 1970-01-01
    • 2016-02-14
    • 1970-01-01
    • 2017-11-09
    • 1970-01-01
    • 1970-01-01
    • 2011-09-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多