我想知道 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/