contents   index   previous   next

Predefining objects with constructor functions


A constructor function creates an object template. For example, a constructor function to create Rectangle objects might be defined like the following.


function Rectangle(width, height)


   this.width = width;

   this.height = height;



The keyword this is used to refer to the parameters passed to the constructor function and can be conceptually thought of as "this object." To create a Rectangle object, call the constructor function with the "new" operator:


var joe = new Rectangle(3,4)

var sally = new Rectangle(5,3);


This code fragment creates two rectangle objects: one named joe, with a width of 3 and a height of 4, and another named sally, with a width of 5 and a height of 3.


Constructor functions create objects belonging to the same class. Every object created by a constructor function is called an instance of that class. The examples above creates a Rectangle class and two instances of it. All of the instances of a class share the same properties, although a particular instance of the class may have additional properties unique to it. For example, if we add the following line:


joe.motto = "ad astra per aspera";


we add a motto property to the Rectangle joe. But the rectangle sally has no motto property.


Initializers for objects and arrays