Inheritance vs Composition on JavaScript

Inheritance vs Composition on JavaScript

·

2 min read

Some days back I wrote about Composition vs Inheritance in React (Here). Got an amazing response on Twitter. So, in this post, we'll see about Composition vs Inheritance in JavaScript.


Intro

What is Inheritance?

In simple language, inheritance means properties you got from your ancestors. Your parents borrowed some properties from their parents and you borrowed some properties from your parents.

What is composition?

Composition is about creating small functions and creating a bigger and more complete function with them. Think of a function as a brick, composition is how you would make those bricks work together to build a wall or a house.


Implementing Inheritance

class Person {
    eat() {
        console.log('I am eating'); 
    }
    breathe() {
        console.log('I am breathing'); 
    }
    swim() {
        console.log('I love to swim');
    }
}

class Magician extends Person {
    trick () {
        console.log('I am doing a trick'); 
    }
}

let sam = new Magician(); 
let rahul = new Magician(); 
sam.eat();      // "I am eating" 
sam.swim();     // "I love to swim"
sam.trick();    // "I am doing a trick"
rahul.eat();    // "I am eating"
rahul.swim();   // "I love to swim"
rahul.trick();  // "I am doing a trick"

Implementing Composition

const eat = function () {
    return {
        eat: () => { console.log('I am eating');}
    }
}
const swim = function () {
    return {
        swim: () => {console.log('I love to swim');}
    }
}
const trick = function () {
    return {
        trick: () => {console.log('I am doing a trick');}
    }
}
const superMagician = () => {
    return Object.assign(
        {},
        eat(), 
        trick()
    ); 
}
const noviceMagician = () => {
    return Object.assign(
        {},
        eat(), 
        trick()
    ); 
}

Removal.AI - [SPONSOR]

Remove background from multiple images in a single upload straight to your desktop using Bulk Photo Background Remover for Windows.

  • ✅ Drag & Drop Multiple Images
  • ✅ Optimize Product Images
  • ✅ Select Your Background
  • ✅ Set Your Output Size
  • ✅ Exceptional Results

Removal AI

Visit -> Removal AI

Did you find this article valuable?

Support Rahul by becoming a sponsor. Any amount is appreciated!