JavaScript Class Compositions Last Updated : 17 Dec, 2024 Comments Improve Suggest changes Like Article Like Report Class composition is a design pattern used to build complex classes by combining behaviours from multiple sources rather than relying solely on inheritance.Class composition enables combining multiple functionalities in a single object.It is a flexible alternative to inheritance, allowing for better code reuse.Composition avoids tight coupling between classes and promotes modular design.Behavior from multiple classes can be added to a single object. JavaScript const CanFly = { fly() { console.log(`${this.name} is flying!`); } }; const CanSwim = { swim() { console.log(`${this.name} is swimming!`); } }; class Bird { constructor(name) { this.name = name; } } // Adding behaviors through composition Object.assign(Bird.prototype, CanFly); const eagle = new Bird("Eagle"); eagle.fly(); OutputEagle is flying! CanFly is an object containing the fly() method.CanSwim is another object that could be assigned similarly for swimming behavior.The Bird class is created with just a name property, and then fly() is added to its prototype through Object.assign(), giving the Bird class the ability to fly.The eagle.fly() call demonstrates how the behavior is mixed into the Bird instance.Key ConceptsFavor Composition Over Inheritance: Inheritance creates tightly coupled structures that can be hard to manage in complex systems. Composition is more flexible, allowing dynamic assembly of features.Mixin Pattern: A common way to achieve composition in JavaScript by adding methods from one object to another.Delegation: Using objects or functions to delegate tasks without creating a deep inheritance chain.Advantages of CompositionFlexibility: Easily add or remove functionality without affecting other parts of the code.Reusability: Modular code is easier to reuse across different projects.Avoids Fragile Base Class Problem: Changes in base classes won't ripple unpredictably through subclasses.When to Use Class Composition?When multiple classes share behaviors but don’t belong to the same inheritance hierarchy.When you want to avoid deep inheritance chains.For adding independent features, like logging or event handling, without altering existing structures.Potential Drawbacks of CompositionOverhead in managing multiple independent components.Naming conflicts if multiple mixins or modules define methods with the same name.Real-World Use CasesUI Components: React components often use composition to share logic (e.g., Higher Order Components or Hooks).Middleware in Frameworks: Express.js uses composition to stack middleware for request/response handling.Game Development: Characters with behaviors like CanJump, CanShoot, or CanSwim can be built using composition.Class Composition vs InheritanceAspectCompositionInheritanceFlexibilityAllows combining any set of behaviors from multiple sources.A class is bound to a single parent and can only inherit from one class.Code ReusabilityProvides flexibility to reuse specific behaviors across classes.Reuse is confined to a single parent, leading to potential complexity.EncapsulationBehaviors are encapsulated within individual classes and are independent.Tight coupling between parent and child classes can reduce flexibility.MaintainabilityEasier to maintain, as changes in one class don’t affect others unexpectedly.Changes in the parent class can propagate to all child classes. Comment More infoAdvertise with us Next Article Java - Divide the Classes into Packages with Examples D dikshamulchandani1 Follow Improve Article Tags : JavaScript Web Technologies JavaScript-Questions Similar Reads Composition in Java The composition is a design technique in java to implement a has-a relationship. Java Inheritance is used for code reuse purposes and the same we can do by using composition. The composition is achieved by using an instance variable that refers to other objects. If an object contains the other objec 4 min read Classes and Objects in Java In Java, classes and objects are basic concepts of Object Oriented Programming (OOPs) that are used to represent real-world concepts and entities. A class is a template to create objects having similar properties and behavior, or in other words, we can say that a class is a blueprint for objects.An 10 min read Association, Composition and Aggregation in Java In object-oriented programming, relationships between classes play a crucial role in defining how objects interact with each other. Java, being an object-oriented language, provides mechanisms to model these relationships through association, aggregation, and composition. Aggregation, association, a 9 min read Java - Divide the Classes into Packages with Examples Let us first know what is a class and package in Java. Class in java is a model for creating objects. It means that the properties and actions of the objects are written in class. Properties are represented by variables and actions of the objects are represented by methods. So, a class contains vari 6 min read Types of Classes in Java A class is a blueprint in the Java programming language from which an individual object can be built. In Java, we may declare a class by using the class keyword. Class members and functions are declared simply within the class. Classes are required for the creation of Java programs. The object-orien 8 min read Difference Between Aggregation and Composition in Java Aggregation and composition describe the type of relationships between objects when communicating with each other, this might be used in low-level design to depict associations between objects. In this article, we are going to discuss the differences between Aggregation and Composition in Java progr 6 min read Like