我正在努力研究在es6中传达'sibling类的好方法或更好的方法',因为它们根据定义没有真正的父类。
让我更好地解释一下:
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);
所以基本上,我有一些环境,我不需要扩展类,因为我想尽可能地将它们保持为封装。
我有这个顶级课程(不是父母,因为其他人没有继承任何东西)。
问题很简单,在元素之间建立这种沟通的最佳方式是什么。
答案 0 :(得分:2)
您可以将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();