Composition
Last updated
Last updated
In JavaScript, composition refers to a design principle where objects are composed of other objects or behaviors, rather than relying on inheritance.
It promotes code reuse, modularity, and flexibility. Instead of creating complex class hierarchies through inheritance, you build objects by assembling them from smaller, more specialized pieces.
In this example:
We have a Person
class representing a basic object with properties and methods.
We define smaller objects Job
and Hobby
, each encapsulating specific behaviors or properties.
We use a function createPersonWithJobAndHobby
to compose a Person
object with a Job
and a Hobby
.
Finally, we create a person named John with a job and a hobby and demonstrate how the composed object can access all properties and methods from its constituent parts.