【问题标题】:Javascript ES6 Classes compositionJavascript ES6 类组成
【发布时间】:2018-03-29 11:04:08
【问题描述】:

我正在努力寻找一种好的做法或更好的方法来交流引用的“es6 中的兄弟类”,因为根据定义,它们没有真正的父类。

让我解释得更好:

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);

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

我有这个顶级类(不是父类,因为其他人没有继承任何东西)。

问题很简单,在元素之间创建这种通信的最佳方式是什么。

【问题讨论】:

  • 没有最好的方法来做到这一点。你想如何解决这个问题取决于实际情况。您可以进行发布订阅或基于事件的连接、使用回调或直接访问函数。或所有这些的组合。
  • 在我看来,一场比赛有一辆或多辆赛车,而一辆赛车有一位车手。所以Driver 的实例可能应该传递给Car。当然,您也可以颠倒关系并说Driver 驱动Car。如何建模完全取决于您。
  • extend 在显示的代码中没有意义,因为CarRaceDriver 这些类型彼此之间没有可以被描述为继承的关系。
  • 并非如此。但是您的Race 对象可以作为事件广播器处理,并且所有汽车和驾驶员对象都可以将crashstopmount 等事件发布到比赛中,并且任何其他对象(例如 Info 对象)都可以订阅对于比赛中的事件,并会被告知任何参与比赛的对象发生的事件。它基本上只是一个事件发射器和事件监听器。但正如我所说,这在很大程度上取决于确切的用例。
  • “但是这些嵌套类不是一个坏习惯,对吧?” 我不会称它们为“嵌套”。但不,这不是坏习惯。 OOP 就是对“事物”及其相互关系进行建模。

标签: javascript ecmascript-6 multiple-inheritance prototypal-inheritance es6-class


【解决方案1】:

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

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

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

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();

【讨论】:

  • 这就是我的做法,因为这是我在 ES5 中一直在做的事情,但我期待在 ES6 中具有一些优势或类似东西的另一种方法。非常感谢
猜你喜欢
  • 2016-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-09
  • 2018-08-11
  • 2015-08-08
  • 2018-05-08
  • 2017-10-05
相关资源
最近更新 更多