【问题标题】:How to make a variable in Typescript not use this如何使 Typescript 中的变量不使用这个
【发布时间】:2014-06-06 15:06:05
【问题描述】:

我需要创建一个 TS 变量来将外部 this 上下文放入一个函数中,这样我就可以调用它。

    public that = this;

    constructor() {
        $('#start').click(function(){
            $(this).hide();
            that.createLoader();
        });
    }

这个 JS 中的结果,

    function SpaceInvaders() {
        this.that = this;
        $('#start').click(function () {
            $(this).hide();
            this.that.createLoader();
        });
    }

如您所见,this.that.cretaeLoader() 中的生成代码结果实际上是 Jquery DOM 元素。

我是TS新手,请帮忙

【问题讨论】:

  • TypeScript 编译器从不将this. 插入到您在此处显示的表达式之前。您确定您发布的代码是您实际拥有的代码吗?你能发布一个可以在 Playground (typescriptlang.org/Playground) 中编译的示例吗?

标签: javascript typescript this


【解决方案1】:

constructor内声明that

constructor() {
    var that = this;
    $('#start').click(function(){
        $(this).hide();
        that.createLoader();
    });
}

【讨论】:

  • 傻我,需要更多咖啡:)
【解决方案2】:

替代方法是使用一些“绑定到上下文”函数

declare var $:any;
class MyClass {

    createLoader(){}

    constructor() {
        $('#start').click((e)=>{
            $(e.currentTarget).hide();
            this.createLoader();
        });
    }
}

see exemple

【讨论】:

  • 对于那些使用它的人来说,“event.currentTarget”并不总是与“this”相同,所以要注意你在哪里使用它
猜你喜欢
  • 2016-09-23
  • 1970-01-01
  • 1970-01-01
  • 2020-06-20
  • 2022-01-13
  • 1970-01-01
  • 2022-01-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多