Skip to content
Related Articles

Related Articles

Difference between Composition and Inheritance in JavaScript
  • Last Updated : 05 Mar, 2021

JavaScript Composition: Composition means to Compose. Everything in JavaScript is treated as an object even functions in JavaScript are treated as a high-class object. Such objects are quite complex in nature to make large complex objects simple, many small objects are composed together. Thus, we can say that composition is the cleaner, reusable and better solution for such large complex objects.

Example:

Javascript




<script>
  const Motor = {
    accelerate(motorspeed, incrementSpeed) {
      return motorspeed + incrementSpeed;
    },
    decelerate(motorspeed, decrementSpeed) {
      return motorspeed - decrementSpeed;
    },
  };
  
  const StopMotor = {
    stop(motorspeed) {
      this.motorspeed = 0;
  
      return 0;
    },
  };
  
  const Brand = {
    model: "Maxpro",
  };
  
  const Treadmill = function (Design, Motor, StopMotor) {
    const brand = Object.create(Design);
    const motor = Object.create(Motor);
    const stopmotor = Object.create(StopMotor);
    const props = {
      motorspeed: 0,
      model: brand.model,
    };
  
    return {
      set(name, value) {
        props[name] = value;
      },
  
      get(name) {
        return props[name];
      },
  
      log(name) {
        console.log(`${name}: ${props[name]}`);
      },
  
      slowDown() {
        props.motorspeed = motor.decelerate(props.motorspeed, 5);
      },
  
      speedUp() {
        props.motorspeed = motor.accelerate(props.motorspeed, 10);
      },
  
      stop() {
        props.motorspeed = stopmotor.stop(props.motorspeed);
      },
    };
  };
  
  const Treadmill1 = Treadmill(Brand, Motor, StopMotor);
  
  // One can increase & decrease the motorspeed
  // according to their preferences
  Treadmill1.speedUp();
  Treadmill1.log("motorspeed");
  Treadmill1.slowDown();
  Treadmill1.log("motorspeed");
  Treadmill1.stop();
  Treadmill1.log("motorspeed");
  Treadmill1.log("model");
    
  // Let us change the model of Treadmill1 to Powermax
  Treadmill1.set("model", "PowerMax");
  Treadmill1.log("model");
</script>

Output:

"motorspeed: 10"
"motorspeed: 5"
"motorspeed: 0"
"model: Maxpro"
"model: PowerMax"

As it can be seen the above code is much cleaner than the one below because here the machine functionality & Features are all separated. So the class can implement functionality suitable as per their requirements.Treadmill1 can implement the functionality of Treadmill when needed. Now, Treadmill1 can increase its motorspeed, decrease its motorspped, and even change its model name as per requirement. When talked about composition, the Inheritance gets assisted automatically. 

JavaScript Inheritance: Inheritance is gaining some or all traits (functionality) of parent and then providing a relational structure which seems to be a tedious little, Unlike Class Composition which implements each functionality separately so that each and every class can use the functionality according to their requirements. Mixin plays a vital role when it comes to inheritance in JavaScript. Mixin is actually mixing which could be any i.e. car into a vehiclemixin means mixing car to the vehicle. To understand the concept properly let’s take an example of Gym/Excercise Machine which is a fitness machine mixin. motorspeed is used to increase, decrease and stop the machine, the case depicted below is of inheritance as Treadmill1 is assigned the object & all its properties of Treadmill. So, now Treadmill1 can perform all the functions of Treadmill i.e. One can increase the motorspeed, decrease the motospeed, and even set the properties in our case which is brand which was Maxpro before and PowerMax later.



Example:

Javascript




<script>
  const machineMixin = {
    set(name, value) {
      this[name] = value;
    },
  
    get(name) {
      return this[name];
    },
  
    motorspeed: 0,
  
    inclinespeed() {
      this.motorspeed += 10;
      console.log(`Inclinedspeed is: ${this.motorspeed}`);
    },
    declinespeed() {
      this.motorspeed -= 5;
      console.log(`Declinedspeed is: ${this.motorspeed}`);
    },
  
    stopmachine() {
      this.motorspeed = 0;
      console.log(`Now the speed is: ${this.motorspeed}`);
    },
  };
  
  const Treadmill = { brand: "Maxpro", motorspeed: 0 };
  const Treadmill1 = Object.assign({}, Treadmill, machineMixin);
  
  // You can increase the speed of Treadmill1
  Treadmill1.inclinespeed();
  
  // You can even decrease the speed of Treadmill1
  Treadmill1.declinespeed();
  
  // Let's just stop the machine
  Treadmill1.stopmachine();
  
  // It's Time to access the brand of  treadmill1
  console.log(Treadmill1.get("brand"));
  
  // let's change the brand of Treadmill1
  Treadmill1.brand = "PowerMax";
  console.log(Treadmill1.get("brand"));
</script>

Output:

"Inclinedspeed is: 10"
"Declinedspeed is: 5"
"Now the speed is: 0"
"Maxpro"
"PowerMax"

In the output above it is clearly visible that all operations are performed by Treadmill1 which was assigned Treadmill object which possesses machinemixin.At First and foremost, the motorspeed was 0 after applying inclinespeed() method the motorspeed increased by 5 after that decline speed method was performed which reduced the speed by 5 finally stop operation was performed which stopped the machine by making its motor speed zero. The brand was changed from Maxpro to Powermax which shows the power of Inheritance. Given below is the comparision table between Composition & JavaScript.

CompositionInheritance
Follows has-a relationshipFollows is-a relationship
Composition allows code-reuse.Inheritance does not allow code-reuse.
In composition, you will no need to extend classesIn inheritance, you will need to extend classes.
In composition, you will no need to Mixin.In inheritance, Mixin plays a major role
The composition is more flexible.Inheritance is less flexible compared to composition.

Conclusion: Both Inheritance & Composition yields the same result but the way of implementation matters. The composition implementation way is much easily readable & preferable to first inheritance.

Attention reader! Don’t stop learning now. Get hold of all the important JavaScript Courses at a student-friendly price and become industry-ready.

full-stack-img

My Personal Notes arrow_drop_up
Recommended Articles
Page :