Post has been deleted
·
Across the Great Wall, we can reach every corner in the world.

可以这样做没问题,这里 config 的生命周期和 app 一样。

通常需要这样做的时候都会有一种更好的解耦方法,两个类交叉耦合逻辑复杂的时候很难理清,容易出 bug。比如写成订阅模式:

class Config {
  private listeners: ((prop: boolean) => void)[];
  private prop: boolean;

  constructor() {
    this.listeners = [];
    this.prop = true;
  }

  public addListener(listener: (prop: boolean) => void) {
    this.listeners.push(listener);
  }

  public getProp() {
    return this.prop;
  }

  public setProp(prop: boolean) {
    this.prop = prop;
    this.listeners.forEach(listener => listener(prop));
  }

  // remove reference
  public destroy() {
    this.listeners = [];
  }
}

class App {
  public config: Config;

  constructor() {
    this.config = new Config();
    this.config.addListener((prop) => {
        console.log('change to:', prop);
    });
  }
}

const app = new App();
app.config.setProp(false); // change to: false