说我有以下内容:
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;
}
}
有没有办法用打字稿的类语义来实现这个,我应该回到普通的JS吗?
答案 0 :(得分:2)
module Test {
export class Foo {
public A = 123;
public GetA = ()=>{return this.A;}
}
}
请试一试。这是生成的javascript:
var Test;
(function (Test) {
var Foo = (function () {
function Foo() {
var _this = this;
this.A = 123;
this.GetA = function () {
return _this.A;
};
}
return Foo;
})();
Test.Foo = Foo;
})(Test || (Test = {}));
答案 1 :(得分:0)
对于那些遇到此页面的人来说,显然TypeScript的人在这里解决了这个问题: https://github.com/Microsoft/TypeScript/wiki/“this'合打字稿