[英]Javascript ES6 Classes composition
我正在努力交流引用“ 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
class
实例传递给Car
constructor
并在该实例内调用任何方法。
我将在这里重新考虑其结构和业务逻辑,并检查每个组件应处理什么样的责任。
例如,我认为应该由驾驶员来决定何时开车,但是汽车当然应该在准备就绪时发出信号。
因此,汽车不应调用driver.ride
,而应仅向驾驶员发出信号, driver.ride
我正在准备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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.