在对象字面量中使用 getter 和 setter 时,我看不到在 Typescript 中访问外部“this”范围的简单方法。请考虑以下事项:
class Report {
stuff: any[];
options = {
length: 10,
get maxLength() { return REPORT.stuff.length }
}
}
其中 REPORT
想要成为对 Report
对象实例的引用。我意识到我可以通过在构造函数中设置选项并使用 var REPORT = this
或类似的方法来解决这个问题,但似乎不够优雅。有没有办法更干净地做到这一点?
最佳答案
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
关于TypeScript:从文字 getter 访问外部 "this",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33357038/