A constructor is used to define a class of objects. To create a constructor in JavaScript, use the new keyword, followed by a function call. The function that is called is where the constructor is defined. In this function, set any properties that should always be present for the constructor.
Consider the following example:
function Square(intSideLength)
{
this.perimeter = 4*intSideLength;
this.area = 2*intSideLength;
}
In the preceding example, the function is the constructor. Use the this keyword to assign properties directly to the constructor. The constructor is now ready to be used:
var mySquare = new Square(4);
document.write(mySquare.perimeter);
document.write(mySquare.area);