TypeScript:从文字 getter 访问外部 "this"

标签 typescript object-literal

在对象字面量中使用 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/

相关文章:

JavaScript - 迭代表单输入并将值收集为对象中的键值对

typescript - TSLint:WebStorm 中的语言服务执行超时

angular - Firestore 的 getCountFromServer() 出现错误

Angular 2 : Why do I need classes like Hero. ts?

JavaScript 属性访问 : dot notation vs. 括号?

javascript - 对象字面量/初始化程序中的自引用

javascript - Lodash 从 bool 属性等于 true 的对象数组中检索项目的索引

javascript - typescript 错误 : Property 'children' does not exist on type '{ children?: ReactNode; }'

javascript - 将原型(prototype)添加到 JavaScript 对象字面量

c# - 在 C# 中使用匿名类型创建对象文字的问题