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

使用类的构造函数初始化另一个类

  •  0
  • GalAbra  · 技术社区  · 6 年前

    在重构一段代码时,我遇到了一个类,我想用一个泛型类替换它。因此,它应该具有几乎相同的功能,但根据“type”参数。

    为了确保向后兼容,我不想只创建一个新类,而是保留旧类的初始化。

    但是我不知道如何在JavaScript中实现这个结构:

    class Generic {
      constructor(type, data) {
        this.type = type;
        this.data = data;
      }
    
      action() {
        switch(this.type) {
          // Does things dynamically, depending on `this.type`
          case 'old': return `old: ${this.data}`;
          default: return this.data;
        }
      }
    }
    
    class Old {
      constructor(data) {
        // I want this to be equivalent to:
        // new Generic('old', data);
      }
    }
    
    // So this should work seamlessly
    const foo = new Old('Hello');
    const output = foo.action();
    console.log(output);
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Jonas Wilms    6 年前

    您可以扩展泛型:

      class Old extends Generic {
        constructor() {
           super("old");
       }
     }