Javascript ES6 类 组成

Javascript ES6 Classes composition

我正在努力寻找一种好的做法或更好的沟通方式 'sibling classes in es6' 引用因为他们没有真正的 parent class,根据定义。

让我更好地解释一下:

class Car {
  constructor(typeOfMotor){
    this.motor = typeOfMotor;
    this.mount();
    this.addListener();
  }

  mount() {
     // Some async logic here, and this will return true or false;
  }

  addListener(driver) {
    // Here i want to listen this.mount method and,
    // when return true, then call the ride method in the driver
    // If true:
    driver.ride();
  }
}

class Driver {
  constructor(driverName) {
    this.name = driverName;
  }
  ride(){
    console.log('Highway to hell!');
  }
}

class Race {
  constructor() {
    this.init();
  }

  init() {
    this.car = new Car('v8');
    this.driver = new Driver('michael');
  }
}


var race = new Race;
race.car.addListener(race.driver);

所以基本上,我有一些不需要扩展 classes 的环境,因为我想尽可能地封装它们。

而且我有这顶 Class(不是 parent,因为其他人没有继承任何东西,不过)。

问题很简单,在元素之间建立这种交流的最佳方式是什么。

您可以将 Driver class 实例传递给 Car constructor 并调用该实例中的任何方法。

我会重新考虑这里的结构和业务逻辑,并检查每个组件应该处理什么样的职责。
例如,我认为由 driver 决定 何时 开车,但当然汽车应该在准备就绪时发出信号。
所以汽车不应该调用 driver.ride 而只是发出 driver 我已经准备好出发的信号,而 driver 应该调用驾驶功能。
但这当然是有争议的。

这是您的代码的 运行 示例(稍作修改):

class Car {
  constructor(typeOfMotor, driver) {
    this.motor = typeOfMotor;
    this.mounted = this.mount();
    this.driver = driver;
  }

  mount = () => {
    console.log('fetching data...');
    setTimeout(() => {
      this.drive()
    }, 1500)
  }

  drive = () => {
    // Here i want to listen this.mount method and,
    // when return true, then call the ride method in the driver
    // If true:
    this.driver.ride();
  }
}

class Driver {
  constructor(driverName) {
    this.name = driverName;
  }
  ride = () => {
    console.log('Highway to hell!');
  }
}

class Race {
  constructor() {
    this.init();
  }

  init = () => {
    this.driver = new Driver('michael');
    this.car = new Car('v8', this.driver);
  }
}


var race = new Race();