Here is a further example of declaring a constructor, showing how a function can be turned into a method:
/* Destined to be a method
* because it refers to this. */
function circleArea ()
{
return Math.PI * this.radius * this.radius;
}
/* Constructor for type Circle.
* Parameters: a Point and a Number. */
function Circle (centre, radius)
{
this.centre = centre; // Creates centre as property
this.radius = radius;
this.area = circleArea; // Creates method area()
}
// Then create and use objects of this type:
var centre1 = new Point (5, -6);
var circle1 = new Circle (centre1, 12); // Construct a Circle
var area1 = circle1.area ();
var circle2 = new Circle (new Point (0, 0), 10);
alert ("Area of circle2 is " + circle2.area ());
Doing it this way, every object of type Circle has a property called area, which is the method area(). On the next page we will see a slightly better way, so there is only one definition of the method.