【问题标题】:TypeScript: Overwrite instance function in unrelated classTypeScript:覆盖无关类中的实例函数
【发布时间】:2018-04-06 22:41:41
【问题描述】:

我有一个像这样构建的Item

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 类有一个 element 属性来保存其 DOM 元素。

我现在有一个不同的班级,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 实例的功能?谢谢!

【问题讨论】:

    标签: javascript jquery typescript jquery-ui arrow-functions


    【解决方案1】:

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

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

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

    bind函数定义

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

    另外,正如我所见,只有amount 正在发生变化。那么为什么不在Item 中使用一个方法,即setAmount。这将更清洁,更容易实施。

    【讨论】:

    • amount 不与Item 关联,但与InventoryElement 关联。我试图仍然在Item 的工具提示上显示它,也许这是不可能的。
    • 我知道。但是您将金额设置为 Item.element 的属性。那么,当元素对它做出反应时,为什么不将它与 Item 关联呢?
    • 实际上是的,我认为这会更容易,并且可以避免调用上下文和函数绑定等带来的麻烦。谢谢!
    猜你喜欢
    • 2016-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-16
    • 1970-01-01
    • 2015-02-01
    • 1970-01-01
    相关资源
    最近更新 更多