Example of Using a Constructor Function

To create a rectangle object, the following example uses the new operator to call the constructor function:

var joe = new Rectangle(3,4)
var sally = new Rectangle(5,3);

This code creates the following rectangle objects:

  • Joe, with a width of 3 and a height of 4

  • Sally, with a width of 5 and a height of 3

This example creates a Rectangle class and two instances of this class. A constructor function creates objects that belong to the same class. Every object that a constructor function creates is an instance of that class.

Class instances share the same properties, although a single class instance can possess more unique properties. For example, adding the following code to the example adds a motto property to the joe rectangle. The sally rectangle does not include a motto property:

joe.motto = "Be prepared!";