Inheritance in JavaScript

Apart from classes, objects, encapsulation, Inheritance in JavaScript is a very important concept of OOPs, Inheritance can be achieved through prototype-based inheritance. It allows objects to inherit properties and methods from other objects, forming a prototype chain.

Here's an example that demonstrates inheritance in JavaScript using constructor functions:

Example

// Parent constructor function
function Animal(name) {
    this.name = name;
}
// Method defined in the parent's prototype
Animal.prototype.sayHello = function() {
    console.log("Hello, I'm " + this.name);
};
// Child constructor function
function Dog(name, breed) {
    Animal.call(this, name);
    this.breed = breed;
}
// Inheriting from the parent's prototype
Dog.prototype = Object.create(Animal.prototype);
// Method defined in the child's prototype
Dog.prototype.bark = function() {
    console.log("Woof woof!");
};
// Creating an instance of Dog
var dog = new Dog("Buddy", "Golden Retriever");
dog.sayHello(); // Output: Hello, I'm Buddy
dog.bark(); // Output: Woof woof!

In the example above, we have a parent constructor function Animal that sets the name property and defines a sayHello method in its prototype. Then, we define a child constructor function Dog that inherits from Animal. We achieve this by calling Animal.call(this, name) within Dog, which allows Dog instances to inherit the name property from Animal.

Next, we set Dog.prototype to an object created using Object.create(Animal.prototype), establishing the prototype chain between Dog and Animal. Finally, we define a bark method in the Dog prototype.

With the inheritance relationship set up, we can create instances of Dog and access both the inherited sayHello method from Animal and the bark method defined in Dog.

Conclusion

It's important to note that JavaScript also introduced class syntax in ES6, which provides syntactic sugar over the prototype-based inheritance. Under the hood, classesin JavaScript still rely on the prototype chain. The example above can be rewritten using classes as well.


Learn via Video Course

Javascript(English) Logo

Javascript(English)

72966

3 hrs