TypeScript:在对象文字字段中的访问器中访问外部“this”



假设我有代码

class A {
    a = 1;
    o = {
        get b() {
            return this.a; //<--
        }
    }
}

所指向的this实际上指的是o而我真的想访问A的实例。

我想要的这种格式可能吗?(不创建函数和别名)

我认为这最终会给你相同的api,尽管你必须分解类才能做到这一点:

class o {
 constructor(private owner: t) {}
 get b() { return this.owner.a; }
}
class t {
 a = 1
 o = new o(this)
}

最新更新