Composition Delegation Binding Bug
Spot the delegation mistake when favoring composition over inheritance in JavaScript.
Codejavascript
class Engine {
constructor() {
this.running = false;
}
start() {
this.running = true;
return 'Engine started';
}
}
class Car {
constructor() {
this.engine = new Engine();
// expose the engine capability via composition
this.start = this.engine.start;
}
drive() {
const msg = this.start();
return `${msg} | engine.running=${this.engine.running}`;
}
}
const car = new Car();
console.log(car.drive());
// Expected: 'Engine started | engine.running=true'The composed Car never actually starts its Engine's state. What is the bug?