Inheritance

Inheritance is the concept of inheriting some behaviors of another class or object. It helps achieve code reusability and build hierarchy in relationships of classes or objects. Also, inheritance helps you cast similar classes.

JavaScript of ES5 standard doesn't support classes, and so, class inheritance is not possible in JavaScript. However, we can implement prototype inheritance instead of class inheritance. Let's see inheritance in ES5 with examples.

First, create a function named Animal, as follows. Here, we create a function named Animal with two methods: sleep and eat:

var Animal = function() { 
this.sleep = function() {
console.log('sleeping');
}
this.eat = function() {
console.log('eating');
}
}

Now, let's extend this Animal function using the prototype, as shown:

Animal.prototype.bark = function() { 
console.log('barking');
}

Now, we can create an instance of Animal and call the extended function bark, as demonstrated:

var a = new Animal(); 
a.bark();

We can use the Object.Create method to clone a prototype of the parent and create a child object. Then, we can extend the child object by adding methods. Let's create an object named Dog and inherit it from Animal:

var Dog = function() { 
this.bark = new function() {
console.log('barking');
}
}

Now, let's clone the prototype of Animal and inherit all the behavior in the Dog function. Then, we can call the Animal method using the Dog instance, as follows:

Dog.prototype = Object.create(animal.prototype); 
var d = new Dog();
d.sleep();
d.eat();
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset