Skip to main content

Object-Oriented JavaScript

Inheritance vs Composition

0:00
LearnStep 1/3

Choosing the Right Abstraction

JavaScript supports both classical inheritance (via class and extends) and object composition. While inheritance is built into the language syntax, composition is often favored in modern JavaScript development for its flexibility and resilience to change.

1. Class Inheritance

Inheritance allows a class to derive properties and methods from another class. This is an 'is-a' relationship.

javascript

2. The Problem with Inheritance

Deep inheritance chains can be fragile. If you need a FlyingRobotDog, inheriting from both Robot and Dog is impossible in single-inheritance languages like JS. This leads to the 'fragile base class' problem where changes in a parent class break unrelated subclasses.

3. Object Composition

Composition combines simple objects or behaviors to create complex ones. This is a 'has-a' or 'can-do' relationship. It's often implemented using factory functions.

javascript

4. Mixins

Mixins are a way to add functionality to a class without strict inheritance constraints, effectively copying methods from one object to another prototype.