JavaScript Object Composition vs Class Inheritance
Quick answer
Composition assembles behavior by storing or receiving collaborators instead of requiring a subclass relationship. Both composition and inheritance are useful under different contracts.
How it works
Inject a collaborator through a constructor or factory and delegate specific operations to it. This can make behavior replaceable without modifying a class hierarchy. Inheritance is appropriate when the derived object satisfies the base interface and behavioral contract; sharing code alone is not sufficient reason. Composition still requires clear interfaces and ownership of shared mutable state.
function makeQuote(pricing){return {total(n){return pricing.cost(n);}};}const a=makeQuote({cost:n=>n*2}); const b=makeQuote({cost:n=>n*3});console.log(a.total(5),b.total(5));Expected output in Node.js:
10 15The injected collaborator controls the calculation.
class Report { constructor(format){this.format=format;} render(n){return this.format(n);} }const r=new Report(n=>"Total:"+n); console.log(r.render(4));Expected output in Node.js:
Total:4A class can use composition by accepting a function collaborator.
Common mistakes
Do not claim that composition always beats inheritance; compare coupling, substitutability and lifecycle requirements.
Practice
Implement two pricing collaborators with identical inputs and compare their results.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript Object Composition vs Class Inheritance — Knowledge Check
Apply the taught concept and predict the output.
What is a composition-based design using a collaborator?
Why might injection make testing easier?
When is inheritance a reasonable fit?
What is the exact console output in JavaScript Object Composition vs Class Inheritance example 1?
function makeQuote(pricing){return {total(n){return pricing.cost(n);}};}const a=makeQuote({cost:n=>n*2}); const b=makeQuote({cost:n=>n*3});console.log(a.total(5),b.total(5));What is the exact console output in JavaScript Object Composition vs Class Inheritance example 2?
class Report { constructor(format){this.format=format;} render(n){return this.format(n);} }const r=new Report(n=>"Total:"+n); console.log(r.render(4));