我如何使用 es6 类 的组合,就像这个例子使用工厂函数一样?

How do I use composition with es6 classes in the same way as this example does using factory functions?

(请注意这不是重复问题,请参阅下面@Jeff M 的回答)

我正在尝试理解 es6 class 语法。我想以与此代码使用工厂函数相同的方式编写我的 classes:

示例 1:

const barker = (state) => ({
  bark: () => console.log("Woof, I am " + state.name)
});

const driver = (state) => ({
  drive: () => state.position = state.position + state.speed
});

const murderRobotDog = (name) => {
  let state = {
    name,
    speed: 100,
    position: 0
  };
  return Object.assign({},
    barker(state),
    driver(state)
  );
};

const bruno = murderRobotDog("bruno");
bruno.bark(); // "Woof, I am Bruno"

我使用完全不同教程中的 'class' 进行 class 合成的工作示例如下所示:

示例 2:

class Employee {
  constructor(firstName, familyName) {
  this._firstName = firstName;
  this._familyName = familyName;
  }

  getFullName() {
  return `${this._firstName} ${this._familyName}`;
  }
}

class Group {
  constructor(manager /* : Employee */ ) {
    this._manager = manager;
    this._managedEmployees = [];
  }

  addEmployee(employee) {
    this._managedEmployees.push(employee);
  }
}

我明白组合的概念是如何运作的,但这些似乎是非常不同的实现方式。使用工厂的第一个示例似乎是最直观的,但我想使用 es6 class 语法(不要担心为什么 :)

也许我遗漏了一些东西,答案很明显,但我如何以最简单的方式使用 es6 classes 准确地完成示例 1 中所做的事情?谢谢。

我可以看到您正在使用 MPJ 的 "composition" 示例,因此您首先需要知道的是 MPJ got composition completely wrong。 MPJ 实际上 展示的(他没有意识到)是多重继承。这就是为什么有人已经将您的问题标记为另一个多重继承问题的可能重复项。

JavaScript的原型链只支持单继承,ES6类使用原型链后,也只支持单继承。但是使用a little trick,我们仍然可以达到与多重继承相同的效果。

它会是这样的:

const barker = Sup => class extends Sup {
  bark() { console.log("Woof, I am " + this.name) }
}

const driver = Sup => class extends Sup {
  drive() { this.position = this.position + this.speed }
};

class murderRobotDog extends driver(barker(Object)) {
  constructor(name) {
      super();
      this.name = name;
      this.speed = 100;
      this.position = 0;
  }
};

const bruno = new murderRobotDog("bruno");
bruno.bark(); // "Woof, I am Bruno"