首页 > 解决方案 > 构造一个新的可配置类

问题描述

我正在尝试创建可以具有默认值的可配置类,但如果需要,可以更改其配置。

这个想法是应该通过调用在 Test 类的静态属性中指定的类型来实例化类。

// Example
const app = Test.App // should return new instance of App class

另外,如果需要,我们应该配置它

// Example
const configured = Test.App.configure({...configuration}) // Should return new instance

主要问题是 App 构造函数只被调用一次,无论我调用多少次 Test.App - 它只是创建一个单例:(

如果需要 class App { public config: any;

  constructor(a: string) {
    console.log(this);
  }

  public configure(conf: any) {
    this.config = conf;
    return this;
  }
}

class Test {
  public static App = new App('App');
}

class Eval {
  constructor() {
    const a = Test.App.configure({test: true});
    const b = Test.App;

    console.log('Test', a, b);
  }
}

标签: typescript

解决方案


您可以使用 getter 在每次调用时创建一个新对象

class Test {
  public static get App() {return new App('App')};
}

如果您调用Test.App两次,它将是 2 个不同的对象,但是无法预测是否Test.App会调用本身的configure调用将跟随


推荐阅读