TypeScript:从文字 getter 访问外部 "this"
TypeScript: Accessing outer "this" from literal getter
在对象文字中使用 getter 和 setter 时,我看不到在 Typescript 中访问外部 "this" 范围的简单方法。考虑以下因素:
class Report {
stuff: any[];
options = {
length: 10,
get maxLength() { return REPORT.stuff.length }
}
}
其中 REPORT
想要成为对 Report
对象实例的引用。我意识到我可以通过在构造函数中设置选项并使用 var REPORT = this
或类似的方法来解决这个问题,但似乎不够优雅。有没有办法更干净地做到这一点?
您可以利用 lambda 的 this
绑定。
class Report {
stuff: any[];
options = {
length: 10,
maxLength: () => this.stuff.length
}
}
编译为
var Report = (function () {
function Report() {
var _this = this;
this.options = {
length: 10,
maxLength: function () { return _this.stuff.length; }
};
}
return Report;
})();
编辑:这会生成一个函数,而不是像您原来那样的 getter。我以为那是一个打字错误,直到刚才我才知道这是有效的 javascript。
I realize that I can solve this by setting options within the constructor and using a var REPORT = this or similar, but seems inelegant
您可以利用 options
* 在构造函数中定义的事实,而不是在构造函数中设置选项。因此,将 this
存储到 options
中:
class Report {
stuff: any[] = [];
options = {
_report: this,
length: 10,
get maxLength() { return (this._report as Report).stuff.length }
}
}
let foo = new Report();
foo.stuff = [1,2];
console.log(foo.options.maxLength); // 2
在对象文字中使用 getter 和 setter 时,我看不到在 Typescript 中访问外部 "this" 范围的简单方法。考虑以下因素:
class Report {
stuff: any[];
options = {
length: 10,
get maxLength() { return REPORT.stuff.length }
}
}
其中 REPORT
想要成为对 Report
对象实例的引用。我意识到我可以通过在构造函数中设置选项并使用 var REPORT = this
或类似的方法来解决这个问题,但似乎不够优雅。有没有办法更干净地做到这一点?
您可以利用 lambda 的 this
绑定。
class Report {
stuff: any[];
options = {
length: 10,
maxLength: () => this.stuff.length
}
}
编译为
var Report = (function () {
function Report() {
var _this = this;
this.options = {
length: 10,
maxLength: function () { return _this.stuff.length; }
};
}
return Report;
})();
编辑:这会生成一个函数,而不是像您原来那样的 getter。我以为那是一个打字错误,直到刚才我才知道这是有效的 javascript。
I realize that I can solve this by setting options within the constructor and using a var REPORT = this or similar, but seems inelegant
您可以利用 options
* 在构造函数中定义的事实,而不是在构造函数中设置选项。因此,将 this
存储到 options
中:
class Report {
stuff: any[] = [];
options = {
_report: this,
length: 10,
get maxLength() { return (this._report as Report).stuff.length }
}
}
let foo = new Report();
foo.stuff = [1,2];
console.log(foo.options.maxLength); // 2