在回调函数中更改类变量

Changing a class variable in a callback function

本文关键字:类变量 回调 函数      更新时间:2023-09-26

我是打字新手,但我认为这更多是javascript的问题,而不是其他问题——具体来说,我缺乏对如何完成某事的理解。

我需要在回调中设置一个类级别的变量,我不确定如何去做。在我的typescript类中,我有一个带有胖箭头函数的方法。它调用使用回调函数发出ajax请求的对象。

在那个回调中,我想在类上设置一个值。简而言之,这就是我得到的:

 class MyClass extends SomeOtherClass {
 protected entity = new Entity();
 protected getToolbar() {
    toolbarbuttons.push({
        title: 'hello',
        onClick: () => { 
            outsideService.makeAjaxCall(
                {
                    url: 'somewhere_in_cyberspace'
                },
                function (response) {
                    this.entity.name = response.Name;
                }
            );
         }     
    });
  }
}

那段代码不能按原样工作,因为在回调中'this'当然指的是Window而不是我的类。

够公平的,我已经尝试做一些_that = this之前我的onClick处理程序,我不能得到响应值"坚持"处理程序退出后,在这个意义上说,在随后的方法this.entity.name不是什么回调设置它?有什么我能做的,还是我错过了什么?

第二个函数也需要是一个箭头函数:

class MyClass extends SomeOtherClass {
    protected entity = new Entity();
    protected getToolbar() {
        toolbarbuttons.push({
            title: 'hello',
            onClick: () => {
                outsideService.makeAjaxCall({
                    url: 'somewhere_in_cyberspace'
                }, (response) => {
                    this.entity.name = response.Name;
                });
            }
        });
    }
}

编译成:

var MyClass = (function (_super) {
    __extends(MyClass, _super);
    function MyClass() {
        _super.apply(this, arguments);
        this.entity = new Entity();
    }
    MyClass.prototype.getToolbar = function () {
        var _this = this;
        toolbarbuttons.push({
            title: 'hello',
            onClick: function () {
                outsideService.makeAjaxCall({
                    url: 'somewhere_in_cyberspace'
                }, function (response) {
                    _this.entity.name = response.Name;
                });
            }
        });
    };
    return MyClass;
}(SomeOtherClass));

正如你所看到的,typescript将箭头函数转换成一个普通的匿名函数,但它保存了一个引用var _this = this;,然后在最内部的函数中使用。