Section 9.1. Constructors


9.1. Constructors

Chapter 7 showed you how to create a new, empty object either with the object literal {} or with the following expression:

 new Object( ) 

You have also seen other kinds of JavaScript objects created with a similar syntax:

 var array = new Array(10); var today = new Date( ); 

The new operator must be followed by a function invocation. It creates a new object, with no properties and then invokes the function, passing the new object as the value of the this keyword. A function designed to be used with the new operator is called a constructor function or simply a constructor. A constructor's job is to initialize a newly created object, setting any properties that need to be set before the object is used. You can define your own constructor function, simply by writing a function that adds properties to this. The following code defines a constructor and then invokes it twice with the new operator to create two new objects:

 // Define the constructor. // Note how it initializes the object referred to by "this". function Rectangle(w, h) {     this.width = w;     this.height = h;     // Note: no return statement here } // Invoke the constructor to create two Rectangle objects. // We pass the width and height to the constructor // so that it can initialize each new object appropriately. var rect1 = new Rectangle(2, 4);    // rect1 = { width:2, height:4 }; var rect2 = new Rectangle(8.5, 11); // rect2 = { width:8.5, height:11 }; 

Notice how the constructor uses its arguments to initialize properties of the object referred to by the this keyword. You 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 you 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.




JavaScript. The Definitive Guide
JavaScript: The Definitive Guide
ISBN: 0596101996
EAN: 2147483647
Year: 2004
Pages: 767

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net