JumpStart # 34– Inheritance in JavaScript using Prototypes

In this JumpStart, I am going to show how to achieve object inheritance in JavaScript using Prototypes. In JavaScript, there is no concept of classes, so we can achieve inheritance only through objects (plain object or Functions).

Lets create an function of Employee as shown below.

function Employee() {
    this.Name = 0;
    this.Experience = 0;
    this.BaseSalary = 0;
    
    this.GetSalary = function (name, exp, baseSalary) {
        this.Name = name;
        this.Experience = exp;
        this.BaseSalary = baseSalary;
        
        return this.Experience * this.BaseSalary;
    };
}

Lets invoke the Employee function.

var employee = new Employee();
console.log(employee.GetSalary('Rami', 10, 200));

We can see output as expected as 2000.

Now lets create Manager function as shown below.

function Manager() {    
}
Manager.prototype = new Employee();

Now lets invoke the Manager function as shown below.

var manager = new Manager();
console.log(manager.GetSalary('Rami', 10, 200));

So a manager without any extended functionality is just an Employee, and he gets paid same as employee i.e., 2000. But that shouldn’t be the case, so lets override the GetSalary() function of Manager function to double of salary for Manager.

Manager.prototype.GetSalary = function (name, exp, baseSalary) {
    this.Name = name;
    this.Experience = exp;
    this.BaseSalary = baseSalary;
    
    return 2 * this.Experience * this.BaseSalary;
};

.When we invoke our new Manager extension (as shown below), we get 4000.

var manager = new Manager();
console.log(manager.GetSalary('Rami', 10, 200));

In the similar way, we can extend our basic employee to different extensions. For example, we can add a simple function to get the extra benefits compensation which is offered to Manager as follows.

Manager.prototype.GetBenefits = function () {
    return 5500;
};

Now when we execute following command, we see 5500 as output.

var manager = new Manager();
console.log(manager.GetBenefits());

Hope you find this JumpStart useful. Happy Coding!!!

You may also like...

  • Srikar

    Nice explanation.