【问题标题】:Typescript: why doesn't it treat 'this' as Javascript?Typescript:为什么不将“this”视为 Javascript?
【发布时间】:2017-03-01 08:34:02
【问题描述】:

我写了以下代码:

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);

错误是:

错误:(25, 12) TS2339: 类型上不存在属性“历史” 'typeof ClickHandlers'。

据我所知,Typescript 将“this”视为 ClickHanlders 类。但是,我使用'call'调用了函数'ClickHandlers.entityNameClickHandler',所以'this'不一定是包装对象。

【问题讨论】:

  • 这是一个静态方法,然后没有任何实例
  • 好的。那么为什么我给它的“这个”有问题呢?
  • 没有。它不是。这是打字稿问题。
  • Typescript 不绑定静态方法'this。它编译为正常ClassName.method = function (args) { ...

标签: javascript typescript this


【解决方案1】:

由于您要在函数内部更改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);
    }
}

【讨论】:

    【解决方案2】:

    如果你想使用 Typescript,你必须忘记 javascript。 即使代码正常工作,Typescript 也会引发错误。它是 javascript,有很多现在你不能做的事情,但你会得到更清晰的代码和更少的错误。

    错误:(25, 12) TS2339: 类型“typeof ClickHandlers”上不存在属性“历史”。

    这个错误表示如果你想使用 this.[property],这个属性应该被定义为一个类变量或在任何父类中。

    正如我在这里看到的:this.refreshEntityContentElem(this);,我知道你应该阅读面向对象编程的教程。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-19
      • 1970-01-01
      • 1970-01-01
      • 2015-08-10
      • 2010-09-09
      • 1970-01-01
      • 1970-01-01
      • 2016-11-05
      相关资源
      最近更新 更多