代码之家  ›  专栏  ›  技术社区  ›  POV

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

  •  1
  • POV  · 技术社区  · 6 年前

    我的课程结构如下:

    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 类,我尝试根据创建实例 registryFilterClasses . 如何正确创建实例?

    我试着这样做:

    class SingletonClassRegister {
      public registeredClasses = {};
    
      public constructor() {
        for (let obj of registryFilterClasses) {
          registryFilterClasses[obj.constructor.name] = new obj();
        }
      }
    }
    

    对吗?

    1 回复  |  直到 6 年前
        1
  •  2
  •   Christoph Lütjen    6 年前

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