TypeScript:覆盖不相关的实例函数 class

TypeScript: Overwrite instance function in unrelated class

我有一个 Item Class 像这样建造的

export class Item {

    element:JQuery<HTMLElement>

    constructor(...) {
        this.element = $("<div >...</div>");
        ...
        this._tooltipUpdate();
        this.element.tooltip({
            items: "div[data-tooltip]",
            content: this.element.attr("data-tooltip"),
            open: this._tooltipUpdate,
            ...
        });

    }

    ...

    public _tooltipUpdate = ():void => {
        this.element.attr(
            "data-tooltip",
            `...`
        );
    };

}

基本上,Item Class 有一个 element 属性来保存它的 DOM 元素。

我现在有一个不同的 class, InventoryElement

export class InventoryElement extends MenuElement {

    amount:number;

    constructor(item:Item) {
        super(...)

        this.amount = 0;

        ...

        this.item._tooltipUpdate = () => {
            this.element.attr(
                "data-tooltip",
                `${this.amount}`
            );
        }
    }
}

InventoryElementItem 实例基本上应该具有不同的 _tooltipUpdate 功能。 目前,它没有正确覆盖它。 我之前在 Item 上实现了 _tooltipUpdate

_tooltipUpdate() {
    ...
}

但我读到这会将其实现为原型函数,而不是上面带有箭头运算符的实例函数。

我是否正确使用了箭头功能?如何更改 Item 实例的功能?谢谢!

使用箭头函数时,您将 this 绑定到 InventoryElement 类型的调用实例。

如果你想在Item中调用this.element,你需要做

this.item._tooltipUpdate = function() {
    // this is now bound to Item
}.bind(this.item);

参见bind函数定义

一般来说,我不认为你这样做的方式是最好的方式。 看起来你的 _tooltipUpdate 就像一个处理程序,它使你能够对项目内的更改做出反应。实现一些事件逻辑然后将侦听器附加到它总是更好。

此外,据我所知,只有 amount 正在发生变化。那么为什么不在 Item 中有一个方法说 setAmount。这将更清晰,更容易实施。