首先,我认为您需要一个数组,所以让我们修复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));
}
}