【发布时间】: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