从外部类访问内部类的成员 - TypeScript

Ram*_*ani 5 namespaces class inner-classes typescript

我正在尝试在 TypeScript 中对班级的一些成员进行分组。考虑下面的类:

export class MyClass {

  private member: string = 'foo';

  public getFoo(): string {

    this._doSomething();

    return this.member;

  }

  // Helper
  _doSomething() { console.log(this.member); }

}
Run Code Online (Sandbox Code Playgroud)

我基本上想做的是用_doSomething命名空间包装(让我们称之为命名空间helpers),这样getFoo()我就可以在里面调用this.helpers._doSomething().

当然,这在 Javascript 中非常容易做到,因为我们可以将对象定义为成员并在对象内部定义辅助函数。

在 TypeScript 中,我通过类表达式几乎得到了同样的效果:

export class MyClass {

  private member: string = 'foo';

  public getFoo(): string {

    this.helpers._doSomething();

    return this.member;

  }

  private helpers = class {

    // To have access to the parent's members
    constructor(private parent: MyClass) { }

    public _doSomething() { console.log(this.parent.member); }

  };

}
Run Code Online (Sandbox Code Playgroud)

唯一的问题是无法MyClass访问helpers类成员。

如何从外部类访问内部类成员?

有没有更好的方法来实现命名空间helpers

任何帮助,将不胜感激。


更新

使用已接受的答案可以实现目标:

export class MyClass {

  private member: string = 'foo';

  public getFoo(): string {

    this.helpers._doSomething();

    return this.member;

  }

  private helpers = new (class {

    // To have access to the parent's members
    constructor(private parent: MyClass) { }

    public _doSomething() { console.log(this.parent.member); }

  })(this);

}
Run Code Online (Sandbox Code Playgroud)

Tit*_*mir 4

您刚刚定义了该类,要访问非静态成员,您必须对其进行新建。您可以像这样内联执行此操作:

export class MyClass {

  private member: string = 'foo';

  public getFoo(): string {

    this.helpers._doSomething();

    return this.member;

  }

  private helpers = new (class {

    // To have access to the parent's members
    constructor(private parent: MyClass) { }

    public _doSomething() { console.log(this.parent.member); }

  })(this);

}
Run Code Online (Sandbox Code Playgroud)

或者,如果您想拥有辅助类的多个实例,您可以根据需要对其进行新创建:

public getFoo(): string {

  let h = new this.helpers(this);
  let h1 = new this.helpers(this);
  h._doSomething();
  h1._doSomething();
  return this.member;

}
Run Code Online (Sandbox Code Playgroud)

您可以通过使用类和命名空间的合并来实现类似的效果,问题是您将无权访问私有成员,而您的解决方案需要这样做:

export class MyClass {
  // Must be public for access from helper
  public member: string = 'foo';

  public getFoo(): string {
    let h = new MyClass.helpers(this);
    h._doSomething();
    return this.member;
  }
}

export namespace MyClass {
  // must be exported to be accesible from the class
  export class helpers {
    // To have access to the parent's members
    constructor(private parent: MyClass) { }
    public _doSomething() { console.log(this.parent.member); }
  }
}
Run Code Online (Sandbox Code Playgroud)