JavaScript Class Compositions Last Updated : 17 Dec, 2024 Comments Improve Suggest changes 1 Likes 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. Create Quiz Comment D dikshamulchandani1 Follow 1 Improve D dikshamulchandani1 Follow 1 Improve Article Tags : JavaScript Web Technologies JavaScript-Questions Explore JavaScript BasicsIntroduction to JavaScript4 min readVariables and Datatypes in JavaScript6 min readJavaScript Operators5 min readControl Statements in JavaScript4 min readArray & StringJavaScript Arrays7 min readJavaScript Array Methods7 min readJavaScript Strings5 min readJavaScript String Methods9 min readFunction & ObjectFunctions in JavaScript5 min readJavaScript Function Expression3 min readFunction Overloading in JavaScript4 min readObjects in JavaScript4 min readJavaScript Object Constructors4 min readOOPObject Oriented Programming in JavaScript3 min readClasses and Objects in JavaScript4 min readWhat Are Access Modifiers In JavaScript ?5 min readJavaScript Constructor Method7 min readAsynchronous JavaScriptAsynchronous JavaScript2 min readJavaScript Callbacks4 min readJavaScript Promise4 min readEvent Loop in JavaScript4 min readAsync and Await in JavaScript2 min readException HandlingJavascript Error and Exceptional Handling6 min readJavaScript Errors Throw and Try to Catch2 min readHow to create custom errors in JavaScript ?2 min readJavaScript TypeError - Invalid Array.prototype.sort argument1 min readDOMHTML DOM (Document Object Model)8 min readHow to select DOM Elements in JavaScript ?3 min readJavaScript Custom Events4 min readJavaScript addEventListener() with Examples9 min readAdvanced TopicsClosure in JavaScript4 min readJavaScript Hoisting6 min readScope of Variables in JavaScript3 min readJavaScript Higher Order Functions7 min readDebugging in JavaScript4 min read Like