【发布时间】:2021-04-29 22:46:02
【问题描述】:
假设我有以下:
module Test {
export class Foo {
public A = 123;
public GetA() {
return this.A;
}
}
}
编译成
var Test;
(function (Test) {
var Foo = (function () {
function Foo() {
this.A = 123;
}
Foo.prototype.GetA = function () {
return this.A;
};
return Foo;
})();
Test.Foo = Foo;
})(Test || (Test = {}));
这一切都很好,但我有一个案例,GetA 将在不同对象的上下文中运行,所以我需要在闭包中捕获“this”。
所以基本上我需要这个JS:
function Foo() {
this.A = 123;
var self = this;
this.GetA = function () {
return self.A;
}
}
有没有办法通过 typescript 的类语义来实现这一点,我应该回退到纯 JS 吗?
【问题讨论】:
-
你如何在不同对象的上下文中执行
GetA? -
大多数情况下,当您将函数作为回调提供时(例如,promise 回调、事件等......)
标签: typescript