Difference between Composition and Inheritance in JavaScript - GeeksforGeeks

26 Jan, 2022
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/Exercise 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 comparison table between Composition & JavaScript.
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.
simranarora5sos
adnanirshad158
javascript-object
javascript-oop
Technical Scripter 2020
JavaScript
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
How to get character array from string in JavaScript?
How to get selected value in dropdown list using JavaScript ?
How to remove duplicate elements from JavaScript Array ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?