我写了下面的代码:
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/