簡體   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