如何在同名子类方法中调用父类方法?

时间:2019-04-28 14:47:26

标签: javascript class

我正在尝试使用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()函数的完整副本。

我是Java的新手,所以我还没有完全了解使用原型的机制-也许最好的解决方案以某种方式涉及到这些?以我的理解,这些方法的工作原理类似,即使定义了原型函数,使用该名称创建函数也将意味着原型都不会被调用。

1 个答案:

答案 0 :(得分:1)

 super.update();

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

相关问题