javascript - typescript :为什么不将 'this' 视为 Javascript?

标签 javascript typescript this

我写了下面的代码:

export class ClickHandlers {
    static entityNameClickHandler(id) {
       console.log("EntityNameClickHandler");        
       // add the new subTree to the end of historySubTree
       this.history.addToHistory(id);
       this.refreshEntityContentElem(this);
    }
}

在另一个文件中:

addEventListenersToEntityInExplorer(elem, id) {
      elem.find('[data-id ^= "expand_"]').click(ClickHandlers.expandButtonHandler);
      elem.find('[data-id ^= "entity"]').click(function() {
         ClickHandlers.entityNameClickHandler.call(this, id)
      }.bind(this));

}

我收到以下行的错误: this.history.addToHistory(id); this.refreshEntityContentElem(this);

错误是:

Error:(25, 12) TS2339:Property 'history' does not exist on type 'typeof ClickHandlers'.

我的理解是 Typescript 将“this”视为类 ClickHanlders。但是,我使用“call”调用了函数“ClickHandlers.entityNameClickHandler”,因此“this”不一定是包装对象。

最佳答案

由于您要在函数内部更改 this,因此您需要将其告知编译器。
Specifying the type of this for functions typescript 2.0 版以来,您可以这样做:

type MyType = {
    history: any;
    refreshEntityContentElem: (obj: any) => void;
}

export class ClickHandlers {
    static entityNameClickHandler(this: MyType, id) {
       console.log("EntityNameClickHandler");        
       // add the new subTree to the end of historySubTree
       this.history.addToHistory(id);
       this.refreshEntityContentElem(this);
    }
}

关于javascript - typescript :为什么不将 'this' 视为 Javascript?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42526823/

相关文章:

reactjs - 导入文件时用 typescript 开 Jest 会引发错误

c# - 在 C#.NET 的方法签名中传递 'this' 的 VB.NET 等价物是什么?

java - "x.this"和 "x.class"是什么意思? (安卓工作室)

angular - Angular4 HttpClient.get() 什么时候返回未定义?

jquery - 将 $ ("#myId").val() 与 $(this).val() 组合

javascript - 如何使用 Javascript/jQuery 在 URL 中添加或替换查询参数?

javascript - 如何在单击按钮时动态实例化全日历

javascript - 如何直接更改svg中的 'transform'属性?

javascript - jQuery 在滚动时调整菜单栏的大小并改变图像

javascript - 如何优化此计算器中的类型描述?