While building web applications using JavaScript, you have to deal with similar types of objects. Inheritance is an important concept in object-oriented programming (OOP) that allows one class or object to inherit properties and behaviors from the parent class. Instead of writing the same code repeatedly, JavaScript Inheritance helps you to reuse code in a clean and organized manner. If you want your code to be efficient, structured, and reduce duplication, then it is important for you to learn JavaScript Inheritance.
In this blog, you will learn everything about inheritance in JavaScript, what it is, how it works, and the different ways you can implement it. So let’s get started!
Table of Contents:
What is Inheritance in JavaScript?
Inheritance in JavaScript means one object can inherit the properties and methods of another object. You can think of it like a family tree. Just like the children get certain traits from their parents, objects in JavaScript can also get properties and behaviors from their parent objects. This helps you to avoid writing the same code again and again.
JavaScript Inheritance works with the help of something called prototypes. These prototypes are used to create a chain between objects so that they can share features easily. Hence, with the help of Inheritance, your code looks simpler, cleaner, and more organized, just like learning good habits from parents and elders. A sample code for Inheritance in JavaScript is given below for your reference:
Code:
Output:
Explanation:
The above code shows JavaScript inheritance using functions. The function named Vehicle defines two properties (brand, model) and a start method. The Car function reuses the Vehicle properties by using call and then inherits its methods using Object.create. It also adds its own method named showDetails. When a Car object is created, it uses both start from Vehicle and showDetails from Car. This helps you to reuse the code and keep things organized.
Boost Your Resume With Real Skills
Join Our Web Dev Course
How does Inheritance Work in JavaScript?
In JavaScript, inheritance works with the help of a system called prototypes. Every object that you create in JavaScript is secretly connected to another object. This connection is called [[Prototype]]. When you try to use a method or inherit a property from an object, JavaScript looks at the object first. If it does not find what you need, it moves up the chain to its prototype and looks for it there. This process is called the prototype chain. This is how one object inherits features from another through inheritance.
Given below is a sample code that shows the working of Inheritance in JavaScript.
Code:
Output:
Explanation:
The above code is an example of JavaScript inheritance using Object.create(). The object named animal has a property canEat and a method eat(). When you create an object named dog using Object.create(animal), it inherits every property from animal with the help of the prototype chain. You can also add a new property called breed directly to the dog. This shows how an object inherits features from another object while also having its own unique properties. This helps to make your code cleaner and efficient.
Types of Inheritance
Here, we will discuss the different types of inheritance along with their code examples.
1. Prototype-based inheritance
Prototype-based inheritance is a type of inheritance in JavaScript where one object can inherit properties from another object. Instead of using classes like other languages, JavaScript connects objects directly to a prototype. This means that if an object does not have what you want, JavaScript looks for its prototype and uses it from there. It is a simple way to share features between objects. A sample code for Prototype-based inheritance is given below for your reference:
Code:
Output:
Explanation:
The above code shows the working of prototype-based inheritance in JavaScript. The object named animal consists of a property named sound and a method named makeSound. After that, a new object named cat is created using Object.create(animal), which means that cat inherits its properties from animal. After that, the sound property is changed in the cat to “Meow”. After cat.makeSound() is called, it uses the inherited method but with its own sound. This shows how objects can share behavior while keeping their own values with the help of JavaScript inheritance.
2. ES6 Class-based Inheritance
ES6 class-based inheritance is a modern and cleaner way to use JavaScript inheritance. Instead of manually using functions and prototypes, you can use the class keyword to define the blueprints for objects. The child class inherits properties from the parent class using the extends keyword. Also, for calling the constructor of the parent class, you can use super() inside the child class. This helps you to read and manage your code in an easier way. A sample code for ES6 Class-based Inheritance is given below for your reference:
Code:
Output:
Explanation:
The above code shows JavaScript inheritance using ES6 classes. The animal class consists of a property named sound and a method named makeSound(). The Cat class extends the Animal class, which means that it inherits the properties and methods from the Animal class. Inside the Cat constructor, super(“Meow”) calls the constructor of the parent class and sets the sound. When you create an object named Cat and then call makeSound(), you can get the output.
3. Mixins for Inheritance
Mixins for Inheritance in JavaScript are a way to add features from multiple parent classes into a single child class. Unlike class-based inheritance, where one class inherits properties from its parent class, mixins help you to combine properties from multiple classes. This can be helpful when you want to reuse methods across objects that are not related without creating any deep class hierarchies. With the help of mixins, you can copy the shared methods into your object. A sample code is given below for your reference:
Code:
Output:
Explanation:
The above code shows how JavaScript inheritance can be done using mixins. Two separate objects, canWalk and canSwim, have methods for walking and swimming. The object named person has a property called name. The Object.assign() function is used to copy the methods from both the mixins into the person object. Now, person can walk and swim without inheriting the properties from a class, which makes the code simple and flexible.
Get 100% Hike!
Master Most in Demand Skills Now!
4. Inheritance with Object.create()
Inheritance with Object.create() is a simple way to set up JavaScript inheritance between two objects. Instead of using classes or constructor functions, you can create a new object directly that links to the existing one. This means that the new object has access to all the properties of the original object through the prototype chain. It is a very easy way to reuse code, especially when you want one object to behave like the other. A sample code is given below for your reference:
Code:
Output:
Explanation:
The above code shows JavaScript inheritance using the Object.create() function. The object named animal has a type and a method named makeSound(). The object named dog is created to inherit from the object named animal. After setting dog.type to “Dog”, dog.makeSound() uses the inherited method, which then prints the output.
5. Inheritance with Object.setPrototypeOf()
Inheritance with Object.setPrototypeOf() is another way to set up JavaScript inheritance between two objects. You can take an existing object instead of creating a new object and link its prototype to another object manually. This helps the child object inherit properties and methods from the parent object. It is a more direct approach, but it is used when you need to change the prototype of an object after it is created. This method also uses the prototype chain, just like other types of inheritance. A sample code is given below for your reference:
Code:
Output:
Explanation:
In the above code, the cat object is linked to the animal object using Object.setPrototypeOf(), so that it can use the makeSound() method from the animal. Even though cat doesn’t have the makeSound(), it inherits it from the prototype chain.
6. Factory functions for Inheritance
In JavaScript, factory functions are regular functions that return objects. They can be used to create multiple similar objects without using any classes or constructors. In order to get inheritance using factory functions, you can create only one factory function that returns a common behavior, and then combine it with other factory functions. In this way, you can share functionality across multiple objects in a clean and flexible way without depending on the prototype chain or ES6 classes. A sample code is given below for your reference:
Code:
Output:
Explanation:
The above code used factory functions to create reusable objects. The animal function returns a generic sound-maker. The cat function builds on it by adding a type class and reusing the properties from the animal class. This shows how you can get inheritance-like behavior without directly using any classes or prototypes.
Advantages of Inheritance in JavaScript
1. Code Reusability: Inheritance helps you to use the same functions and properties in different objects without writing them again and again.
2. Easy to Update: If anything is changed in the parent class, all the child classes automatically get updated.
3. Organized code: Inheritance helps you to follow a clear and consistent structure. Therefore, it becomes easy to work with your code.
4. Saves memory: All the common functions are stored in one place and shared. This helps you to ensure that your code does not waste memory by copying the same code for every object.
Best Practices for JavaScript Inheritance
1. You should build objects by combining smaller parts instead of creating deep inheritance chains.
2. The modern class syntax makes your code cleaner and easier to read.
3. It is important for you to understand how the prototypes work because it helps you to debug and structure your code in a better way.
4. You should always use super() before you access this in a subclass constructor to avoid errors.
5. You need to keep your inheritance shallow to make your code easier to understand.
Conclusion
JavaScript Inheritance is an important concept. It helps you reuse your code, structure your reasoning, and form adaptable structures in your programs, regardless of whether you are working on class-based inheritance, prototypes, or mixins. Knowledge of how JavaScript Inheritance works will make your code look clean and more precise. By following the best practices and keeping things simple, you will understand the full potential of JavaScript inheritance in your projects. If you are an aspiring web developer, explore our blog and enroll in our Web Development course.
Inheritance in JavaScript – FAQs
Q1. Is JavaScript inheritance only useful for big projects?
No, inheritance is useful even when applied to small projects because it keeps code well organized and reusable.
Q2. Can I combine multiple inheritance types in one project?
Yes, it is a normal thing to use different types of inheritance together, like classes and Object.create(). They help to make your code more flexible.
Q3. Does inheritance slow down the performance?
Not really, if used wisely, it can make your code faster and more efficient to manage.
Q4. Is it okay to override parent methods in child objects?
Yes, that is not an issue. You just need to make sure you know what the original method does so that you don’t break how things work.
Q5. Do I always need to use inheritance in JavaScript?
No, it is not compulsory. Only use it when it makes your code easier to understand and manage.