Monday, August 10, 2009

Inheritence in Javascript

Example of Inheritence in Javascript:

function Person(name) {
this.name = name;

this.printName = function() {
alert("Name is "+this.name);
}
}


function Employee(name, sal) {
Person.call(this, name);
this.sal = sal;

this.printSalary = function() {
alert("Salary is "+this.sal);
}
}


function NonFunctionalEmployee(name, sal, hours) {
Employee.call(this, name, sal);
this.hours = hours;

this.printHours = function() {
alert("Number of hours of work "+this.hours);
}
}

var nonFunctionalEmp = new NonFunctionalEmployee("XYZ", 3333, 12);
nonFunctionalEmp.printName();
nonFunctionalEmp.printSalary();
nonFunctionalEmp.printHours();

call(this) is the main api which helps in inheritence.
The "this" parameter specifies the context in which the call() should get executed.

No comments:

Post a Comment