我正在尝试使用 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}`);
Run Code Online (Sandbox Code Playgroud)
这会产生输出:
Start pos: 0, 0
End pos: 0, 10
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,y 位置通过调用 正确更新XYmover.update(),但这个新定义覆盖了对 的任何调用Xmover.update()。如果两个函数都被调用,我们期望看到结束位置10, 10.
我见过不使用此类语法的人通过以类似于以下方式创建原始 super 函数的副本来解决此问题:
Start pos: 0, 0
End pos: 0, 10
Run Code Online (Sandbox Code Playgroud)
然而,这对我来说并不理想,而且它也不适用于类语法(除非您super_update在子类构造函数中定义它,这似乎会产生其他问题,因为parent.update()在子对象的每个实例)。
我是 Javascript 新手,所以我还没有完全了解使用原型的机制 - 也许最好的解决方案以某种方式涉及这些?然而,在我的理解水平上,它们的工作方式类似,因为即使定义了原型函数,创建具有该名称的函数也意味着原型永远不会被调用。