Next page | Contents page |

Prototypes

Objects inherit from a prototype object (of type Object), created by the constructor. There is only one prototype object for each class, so put constants and methods there, just once rather than on every object of the class. Eg,


/* Constructor */
function Circle (centrePoint, radius)
{
  this.centre = centrePoint;
  this.radius = radius;
}

Circle.prototype.PI = 3.145926; // Constant PI

function circleArea ()
{
  return this.PI * this.radius * this.radius; 
}

Circle.prototype.area = circleArea; // Method area ()

var c = new Circle ({ x:1, y:2}, 3);	
alert ("Area = " + c.area ());

We could have declared the area() function as a method all in one step, in which case the function declaration does not need a name, arguably the best way:


Circle.prototype.area = function ()
{
  return this.PI * this.radius * this.radius; 
}

Built-in (predefined) objects also have prototype objects to which you can add properties.

Curious aspects of prototypes

You need to be aware of these.

Next page | Contents page |