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

时间:2020-04-26 10:21:09

标签: javascript

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

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

但是我不确定如何在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 个答案:

答案 0 :(得分:1)

您可以扩展泛型:

  class Old extends Generic {
    constructor() {
       super("old");
   }
 }
相关问题