Sunday, March 27, 2011

Object inheritance with Javascript

Prototype can be used to define data member and function member to a object. It also is used to realize inheritance for javascript. In order to inherit an object from another object, we set the new the new function's prototype to the existing function as show below:
function base()
{ this.inbase = 2;}

base.prototype.inbaseProto = 3;
base.prototype.getint = function()
{
return 3;
}

derived.prototype = new base;
function derived()
{ this.inderived = 4;}

derived.prototype.inderivedProto = 5;

x = new derived;
s = x.getint();

alert(base.inbase + ', ' + x.inbaseProto + ', ' + x.inderived + ', ' + x.inderivedProto + ', ' + s );
The result is "2, 3, 4, 5, 3";

Jonathan

No comments:

Post a Comment