Javascript ES6 Classes composition

耗尽温柔 提交于 2019-12-13 03:23:46

问题


i'm struggling in what would be a good practice or better approach to communicate 'sibling classes in es6' quoted because they haven't a real parent class, by definition.

let me explain better:

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

So basically, i have some environments where i don't need to extend classes, because i want to keep them as encapsulated as possible.

And i have this top Class (not parent because the others are not inheriting anything, though).

And the question is simple, what would be the best way to create this communication between the elements.


回答1:


You can pass the Driver class instance to the Car constructor and invoke any method within this instance.

I would rethink the structure and business logic here and check what kind of responsibility each component should handle.
For example, i think it's up to the driver to decide when to drive but of course the car should signal when it is ready.
So the car shouldn't invoke driver.ride and instead just signal the driver i'm on and ready to go, and the driver should invoke the driving function.
But that's arguable of course.

Here is a running example of your code (a bit modified):

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


来源:https://stackoverflow.com/questions/46795498/javascript-es6-classes-composition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!