Object-Oriented Programming - Part 2
Written by: Doug Jenkinson
Article
Here's a fairly simple JavaScript OOP example, with inheritance.
First, we define a simple Shape class. This will be the base for our future, more specialized, shapes.
function Shape() { this.area = 0; this.perimeter = 0; }
Shape.prototype.getArea = function() { return(this.area); }
Shape.prototype.getPerimeter = function() { return(this.perimeter); }
I've defined two functions that will be inherited (and could be overloaded if a developer so chose to do so). getArea() simply returns the value of this.area, and the same for getPerimeter().
Now, let's define a new class, a circle, that will use our base class.
Circle.prototype = new Shape();
Circle.prototype.constructor = Circle;
Circle.prototype.baseClass = Shape.prototype.constructor;
function Circle(r) {
this.area = Math.PI * r * r;
this.perimeter = 2 * Math.PI * r;
}
Pretty easy stuff. Our Circle class will inherit the getArea() and getPerimeter() functions from its base class Shape.
Here's another example, a rectangle.
Rectangle.prototype = new Shape();
Rectangle.prototype.constructor = Rectangle;
Rectangle.prototype.baseClass = Shape.prototype.constructor;
function Rectangle(x, y) {
this.area = x * y;
this.perimeter = (2 * x) + (2 * y);
}
Again, the Rectangle class will inherit getArea() and getPerimeter().
Now, to use all these classes, here's a little code example for you.
var circle = new Circle(10);
var rectangle = new Rectangle(10, 20);
alert("Circle base class = " + circle.baseClass);
alert("Circle Area = " + circle.getArea());
alert("Circle Circumference = " + circle.getPerimeter());
alert("Rectangle base class = " + rectangle.baseClass);
alert("Rectangle Area = " + rectangle.getArea());
alert("Rectangle Perimeter= " + rectangle.getPerimeter());
As you can see, the baseClass property shows that the Circle and Rectangle classes were inherited from our Shape class.
Revisions
- v1.0 (10 Mar 2006) - Article published.

