首页 > 解决方案 > 使用类的构造函数初始化另一个类

问题描述

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

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

但是我不确定如何在 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);

标签: javascript

解决方案


您可以扩展通用:

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

推荐阅读