Example of Inheritance using Class, Prototype or Call Javascript methods

Inheritance is the Concept using which you can inherit properties and methods from one Class to another Class. The Class from which we will inherit properties or methods that is Called parent Class. Which Class inherit from Parent Class that is Called Child Class.

This relationship is Similar to Father and Son relationship. You must noticed in major Cases kid inherits properties depending upon his or her parents.

In below I am showing an example of Person and Teacher Classes. My Person Class is having First Name, Last Name, Age and Gender. As teacher as a person my teacher class inherits all the properties of my person class. Additionally I am adding Salary as a new property.

/*Constructor Class*/
function person(firstname, lastname, age, gender) {
this.name = { firstname, lastname };
this.age = age;
this.gender = gender;
};

Normally what we do, The time we Create the Class we design the properties and methods. Think once if we required some additional methods or properties to an existing Class without disturbing the Class, in this scenario prototyping is useful. Look at the below example here I am adding a greeting method to my person Class using Prototyping.

/*Prototyping Person Class*/
person.prototype.greeting = function() {
alert('Hi! I\'m ' + this.name.firstname + '.');
};

Here I am Creating an instance for my Person Class and Calling the method greeting.

var personInstance = new person("Bikash", "Dash", 27, "M", 20000);
personInstance.greeting();

In the below Code I am Creating the teacher Class by inheriting all the properties from Person Class. As the number of arguments known to me, here I used Call to bind person class properties to teacher class.

/*Teacher Class inherits from Person Class*/
function Teacher(firstname, lastname, age, gender, salary) {
person.call(this, firstname, lastname, age, gender);
this.salary = salary;
}

/*To assign Person prototype we have to Create Prototype for Teacher*/
Teacher.prototype = Object.create(person.prototype);
var newTeacher = new Teacher("Baby", "Roy", 26, "F", 30000);
alert(newTeacher.name["firstname"]);
alert(newTeacher.gender);

/*After Teacher.Prototype only this will work*/
newTeacher.greeting();

Here if we alert(Teacher.prototype.constructor); it will show Person Class Constructor. To display Teacher Class Constructor we have to execute the following line of Code.

Teacher.prototype.constructor = Teacher;