我想知道打字稿是否提供了避免臭名昭着的方法:
let that = this
例如,我有一个类调用我订阅的web api,并且在订阅中引用了我的类,我确实为this
创建了一个变量。
class Foo {
f = {}
let that = this
this.http.get(foo)
.subscribe {
res => that.f = res
}
}
答案 0 :(得分:6)
是。使用arrow function时无需let that = this
。箭头函数在词法上绑定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;
}());