如何通过名称或类型创建类的实例?

时间:2018-10-21 19:24:34

标签: typescript

我的班级结构如下:

Multibytes

Wide Chars类的构造函数中,我尝试基于class FilterWeekScheduleClass { } class FilterClassJournal { } const registryFilterClasses = { FilterWeekScheduleClass, FilterClassJournal }; class SingletonClassRegister { public registeredClasses = {}; public constructor() { for (let obj in registryFilterClasses) { // CREATE INSTANCE OF obj LIKE new obj(); } } } let a = new SingletonClassRegister(); 创建实例。如何正确创建实例?

我试图这样做:

SingletonClassRegister

对吗?

1 个答案:

答案 0 :(得分:2)

首先,我认为您需要一个数组,所以让我们修复RegistryFilterClasses:

const registryFilterClasses = [
  FilterWeekScheduleClass,
  FilterClassJournal
];

然后只需创建实例:

for (let cls of registryFilterClasses) {
  let myInstance = new cls();
}

或与对象相同的数据源:

const registryFilterClasses = {
  FilterWeekScheduleClass,
  FilterClassJournal
};
// see https://eslint.org/docs/rules/object-shorthand
// same as
//    const registryFilterClasses = {
//      FilterWeekScheduleClass: FilterWeekScheduleClass,
//      FilterClassJournal: FilterClassJournal
//    };

for (let key in registryFilterClasses) {
  // key is now the name of the class as string
  let myInstance = new registryFilterClasses[key]();
}

更新:获取课程名称:

class Test {}
Test.name => "Test"

const t = Test;
t.name => "Test"

const i = new t();
i.constructor.name => "Test"

可能的注册表实现:

class SingletonClassRegister {
  public registeredClasses = {
    MyClass
  };

  private instances = {};

  getInstanceByClassName(name) {
    if(this.instances[name] == undefined)
      this.instances[name] = new this.registeredClasses[name]();
    return this.instances[name];
  }

  getInstancesForAllRegisteredClasses() {
    return Object.keys(this.registeredClasses)
       .map(name => this.getInstanceByClassName(name));
  }
}