typescript - 有没有办法避免 typescript 中臭名昭著的 that = this

标签 typescript

我想知道 typescript 是否提供了一种避免臭名昭著的方法:

let that = this

例如,我有一个类调用我正在订阅的 web api,为了在订阅中引用该类,我确实为 this 创建了一个变量。 .

class Foo {
   f = {}
   let that = this 
   this.http.get(foo)
   .subscribe {
      res => that.f = res 
   }
}

最佳答案

是的。使用 arrow function 时,let that = this 不是必需的.箭头函数在词法上绑定(bind) this 值。

编写这段代码时请注意:

class Foo {
    f = {};

    someMethod() {
        someFunction(res => this.f = res)
    }
}

ES5 JavaScript 输出为您执行 let that = this(如 var _this = this):

var Foo = (function () {
    function Foo() {
        this.f = {};
    }
    Foo.prototype.someMethod = function () {
        var _this = this;
        someFunction(function (res) { return _this.f = res; });
    };
    return Foo;
}());

关于typescript - 有没有办法避免 typescript 中臭名昭著的 that = this,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37383468/

相关文章:

angularjs - 为什么对 $scope 字段的更改不会传播到另一个字段?

javascript - TS - 使用 return 从回调函数中分配值

javascript - typescript 方法覆盖不起作用

typescript - 找不到 '@wdio/globals/types' 的类型定义文件

javascript - 如何动态选择一个对象来添加属性 - js

typescript - 创建具有其他类型和其他可选属性的通用属性的类型

javascript - 订阅事件时未刷新具有 ChangeDetectorRef 的管道

typescript - 记录: restrict to existing keys with typed entries

typescript - 如何正确定义嵌套对象的泛型类型

javascript - 当属性是可选的时,如何在 Typescript 中解构对象?