繁体   English   中英

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

[英]How to call a parent class method inside a child class method of the same name?

我正在尝试使用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()的完整副本)子对象的每个实例中的parent.update()函数)。

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

 super.update();

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM