Cricinfo Live Scores

Sunday, February 17, 2008

Object Oriented Javascript (Inheritance)

We will see in this article how we can implement inheritence in JavaScript. Superclass and subclass creation and implementation will be shown here.

This is the extend function that creates the superclass and subclass relationship.
function extend(subclass, superclass) {
function Dummy(){}
Dummy.prototype = superclass.prototype;
subclass.prototype = new Dummy();
subclass.prototype.constructor = subclass;
subclass.superclass = superclass;
subclass.superproto = superclass.prototype;
}
Here Person is Super Class. Its toString function is set like this

function() {
return this.first + ' ' + this.last;
};
////////////////////Super Class////////////////
function Person(first, last) {
this.first = first;
this.last = last;
}

Person.prototype.toString = function() {
return this.first + ' ' + this.last;
};

Now we will create a subclass named Employee

////////////////////Sub Class////////////////

function Employee(first, last, id) {
Employee.superclass.call(this, first, last);
this.id = id;
}
extend(Employee, Person);

Employee.prototype.toString = function() {
return Employee.superproto.toString.call(this) + ': ' + this.id;
};


Output of the html will be like this

John Dough
Bill Joi: 100

References:
http://kevlindev.com/tutorials/javascript/inheritance/index.htm

Author:
Kazi Masudul Alam
Software Engineer