Composition
Composition is a form of association that occurs when an object's life is tightly bound to another object's life. When the main object dies (i.e., is deleted), all the objects that are associated with that object also die. This means that the referenced object is solely contained by the referring object.
There are a lot of real-life examples of composition in OOP. We are going to present the most used composition example here: the Vehicle example.
1// Vehicle.js
2class Vehicle {
3 constructor() {
4 this.wheels = Array(4).fill(new Wheel());
5 this.doors = Array(4).fill(new Door());
6 this.seats = Array(4).fill(new Seat());
7 }
8
9 mode(a, b) {
10 // Moving
11 }
12}
13
14// index.js
15const vehicle = new Vehicle();
16// Do something with Vehicle
17// The Wheel, Door, and seats will be garbage collected when they're no longer in use
Note that you cannot keep the Door
or any other object alive after destroying the Vehicle
object. This is why it's called composition: the Vehicle
class/object is composed of Doors, Wheels, and Seats.