8.2 ConstructorsWe saw previously that you can create and initialize a new object in JavaScript by using the new operator in conjunction with a predefined constructor function such as Object( ), Date( ), or Function( ). These predefined constructors and the built-in object types they create are useful in many instances. However, in object-oriented programming, it is also common to work with custom object types defined by your program. For example, if you are writing a program that manipulates rectangles, you might want to represent rectangles with a special type, or class, of object. Each object of this Rectangle class would have a width property and a height property, since those are the essential defining characteristics of rectangles. To create objects with properties such as width and height already defined, we need to write a constructor to create and initialize these properties in a new object. A constructor is a JavaScript function with two special features:
Example 8-1 shows how the constructor function for a Rectangle object might be defined and invoked. Example 8-1. A Rectangle object constructor function// Define the constructor. // Note how it initializes the object referred to by "this". function Rectangle(w, h) { this.width = w; this.height = h; } // Invoke the constructor to create two Rectangle objects. // We pass the width and height to the constructor, // so it can initialize each new object appropriately. var rect1 = new Rectangle(2, 4); var rect2 = new Rectangle(8.5, 11); Notice how the constructor uses its arguments to initialize properties of the object referred to by the this keyword. Keep in mind that a constructor function simply initializes the specified object; it does not have to return that object. We have defined a class of objects simply by defining an appropriate constructor function -- all objects created with the Rectangle( ) constructor are now guaranteed to have initialized width and height properties. This means that we can write programs that rely on this fact and treat all Rectangle objects uniformly. Because every constructor defines a class of objects, it is stylistically important to give a constructor function a name that indicates the class of objects it creates. Creating a rectangle with new Rectangle(1,2) is a lot more intuitive than with new init_rect(1,2), for example. Constructor functions typically do not have return values. They initialize the object passed as the value of this and return nothing. However, a constructor is allowed to return an object value, and, if it does so, that returned object becomes the value of the new expression. In this case, the object that was the value of this is simply discarded. |