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...