OOP in JavaScript - Part 3: Extending classes

Permanent Link: OOP in JavaScript - Part 3: Extending classes 22. September 2009 RSS Feed for comments on RSS-Feed für Kommentare zu: OOP in JavaScript - Part 3: Extending classes comments feed

After I've already covered normal and static classes, Part 3 is about extending classes. As before, basic knowledge in OOP and JavaScript is needed.

First, let's create a class Human with setters and getters for the age:

function Human()
{

}

Human.prototype._age = 0;

Human.prototype.setAge = function(age)
{
if (typeof age != 'number') {
throw('Invalid Age provided');
}
this._age = age;
};

Human.prototype.getAge = function()
{
return this._age;
};

Since there are no keywords like class, private, public or protected in Javascript it's no surprise there's no keyword extends aswell. In order to extend a class you have to use prototyping:

function Woman(age)
{
    this.setAge(age);
}

Woman.prototype = new Human();

Now we've created a new class Woman that inherits all methods and properties from Human by assigning Woman's prototype to new Human(). To show it's easily possible, I've also changed the constructor as it now takes age as parameter. Creating a new object Woman and reading the age looks like this:

var woman = new Woman(22);
alert(woman.getAge());

You can overload methods simply by redifining them. In this case we'll overload the getAge method where we'll add an additional check and then call the parent getAge method. Since you actually don't call the parent method but call the parent method in static way, it is important to add call(this) in order to call the method in the actual context.

Woman.prototype.getAge = function()
{
if (this._age > 100) {
throw('This person is probably already dead!');
}
return Human.prototype.getAge.call(this);
};

Multiple inheritance is possible, but not very easy. For a method using Swiss Inheritance, check this page. Extending static classes might be possible, but I don't know a way. Problem is you need to clone the parent class (which is not that easy in JavaScript), if you write it like this the child becomes the parent and the other way round, meaning if you add a method in the Child it is also available in the parent:

function Cookie()
{

}

Cookie.get = function()
{
return 'something';
};

var CookieChild = Cookie;
alert(CookieChild.get());

Part 4 (probably the last one of the series for now) will cover scoping.

0 comments

No Comments yet.

Write a comment

(will not be published)