8.2 User-Defined Objects


8.2 User -Defined Objects

All user-defined objects and built-in objects are descendants of an object called Object .

8.2.1 The new Operator

The new operator is used to create an instance of an object. To create an object, the new operator is followed by the constructor method. In the following example, the constructor methods are Object(), Array() , and Date() . These constructors are built-in JavaScript functions. A reference to the object is returned and assigned to a variable.

 
 var car = new Object(); var friends = new Array("Tom", "Dick", "Harry"); var now= new Date("July 4, 2003"); 

8.2.2 The Object() Constructor

A constructor is a function (or method) that creates (constructs) and initializes an object. JavaScript provides a special constructor function called Object() to build the object. The return value of the Object() constructor is assigned to a variable. The variable contains a reference to the new object. The properties assigned to the object are not variables and are not defined with the var keyword. See Example 8.3.

FORMAT

 
 var myobj = new Object(); 
Example 8.3
 <html>     <head><title>User-defined objects</title> 1       <script language = "javascript"> 2  var toy = new Object();   // Create the object  3           toy.name = "Lego";  // Assign properties to the object  toy.color = "red";             toy.shape = "rectangle"; 4       </script>     </head>     <body bgcolor="lightblue"> 5       <script language = "javascript"> 6           document.write("<b>The toy is  a " +  toy.name  + "."); 7           document.write("<br>It is a " +  toy.color  + " "                            +  toy.shape  + "."); 8       </script>     </body>     </html> 

EXPLANATION

  1. JavaScript code startes here.

  2. The Object() constructor is called with the new keyword to create an instance of an object called toy . A reference to the new object is assigned to the variable, toy .

  3. The toy object's name property is assigned "Lego" . The properties describe the characteristics or attributes of the object. Properties are not variables. Do not use the var keyword.

  4. This is the end of the JavaScript program.

  5. A new JavaScript program starts here in the body of the page.

  6. The global object called toy is available within the script. The value of the toy object's name property is displayed.

  7. The values for the color and shape properties of the toy object are displayed.

  8. This is the end of the JavaScript program. The output is shown in Figure 8.3.

    Figure 8.3. The toy object and its properties.

    graphics/08fig03.jpg

8.2.3 Creating the Object with a User-Defined Function

To create user-defined objects, you can create a function that specifies the object's name, properties, and methods. The function serves as a template or prototype of an object. When the function is called with the new keyword, it acts as a constructor and builds the new object, and then returns a reference to it.

The this keyword is used to refer to the object that has been passed to a function.

Example 8.4
 <html>     <head><title>User-defined objects</title></head>     <script language = "javascript"> 1  function book(title, author, publisher){   // Defining properties  2  this.title = title;  3  this.author = author;  4  this.publisher = publisher;  5  }  </script>     <body bgcolor="lightblue"></body>     <script language = "javascript"> 6       var  myBook = new book("JavaScript by Example",   "Ellie", "Prentice Hall");  7       document.writeln("<b>"  +  myBook.title  +                          "<br>" +  myBook.author  +                          "<br>" +  myBook.publisher  );     </script>     </body>     </html> 

EXPLANATION

  1. This is a user-defined constructor function with three parameters.

  2. The this keyword refers to the current object that is being created. The object is being assigned properties. The title of the book, "JavaScript by Example" , is being passed as the first parameter and assigned to the title property.

  3. The author, "Ellie" , is assigned to the author property.

  4. The publisher, "Prentice Hall" , is assigned to the publisher property.

  5. This is the closing curly brace that terminates the function definition.

  6. The variable, myBook , is assigned a reference to the newly created object.

  7. The title property of the myBook object will be displayed. All of the properties of the book object are displayed in Figure 8.4.

    Figure 8.4. Output from Example 8.4.

    graphics/08fig04.jpg

8.2.4 Defining Methods for an Object

The previous examples demonstrate how the constructor creates the object and assigns properties. But we need to complete the definition of an object by assigning methods to it. The methods are functions that let the object do something or let something be done to it. There is little difference between a function (see Chapter 7, "Functions") and a method, except that a function is a standalone unit of statements and a method is attached to an object and can be referenced by the this keyword.

Example 8.5
 <html>     <head><title>Simple Methods</title>     <script language = "javascript"> 1  function distance(r, t)  {  //  Define the object  2           this.rate = r;        //  Assign properties  this.time = t;         } 3  function calc_distance()  {  //  Define a function that will  //  be used as a method  4           return  this.rate * this.time;  }     </script>     </head>     <body bgcolor="lightblue">     <script language="javascript"> 5       var speed=eval(prompt("What was your speed                               (miles per hour)? ",""));         var elapsed=eval(prompt("How long did the trip take?                                 (hours)?" ,"")); 6  var howfar=new distance(speed, elapsed);  //  Call the constructor  7  howfar.distance=calc_distance;  //  Create a new property  8  var d = howfar.distance();  //  Invoke method  9       alert("The distance is " + d + " miles.");     </script>     </body>     </html> 

EXPLANATION

  1. This is the constructor function. It creates and returns a reference to an object called distance . It takes two parameters, r and t .

  2. The object (referenced by the this keyword) is assigned properties.

  3. The function calc_distance() will be used later as a method for the object.

  4. The function returns the results of this calculation to the variable, d , on line 8.

  5. The user is prompted for input in this statement and the next . (See Figure 8.5.) The string he enters is evaluated by the eval() method and assigned as a number to the variables speed and elapsed .

    Figure 8.5. The user is prompted for input.

    graphics/08fig05.jpg

  6. A new object called howfar is created with the new constructor. Two arguments are passed, the rate (in miles per hour) and the time (in hours).

  7. A new property for the howfar object is created. It is assigned the name of the function, calc_distance , that will be used as a method. Note: only the name of the function is assigned without the parentheses. Putting them there would result in an error.

  8. The method called distance() is invoked for the howfar object. The returned value is assigned to variable, d .

  9. The alert box displays the distance traveled. (See Figure 8.6.)

    Figure 8.6. Final output displayed from Example 8.5.

    graphics/08fig06.jpg

A Method Defined in a Constructor

Methods can automatically be assigned to an object in the constructor function so that the method can be applied to multiple instances of an object.

Example 8.6
 <html>     <head><title>User-defined objects</title>  <script language ="javascript">  1  function book  (title, author, publisher){   //  Receivin  g                                                    //  parameters  2           this.pagenumber=0;      //  Properties  this.title = title;             this.author = author;             this.publisher = publisher; 3  this.uppage = pageForward;  //  Assign function name to  //  a property  4  this.backpage = pageBackward;  } 5  function pageForward()  {   //  Functions to be used as methods  this.pagenumber++;             return this.pagenumber;         } 6  function pageBackward()  {             this.pagenumber--;             return this.pagenumber;         }     </script>     </head>     <body bgcolor="lightblue">     <script language = "javascript"> 7  var myBook = new book("JavaScript by Example", "Ellie",   "Prentice Hall" );  //  Create new object  8       myBook.pagenumber=5; 9       document.write( "<b>"+ myBook.title +                         "<br>" + myBook.author +                         "<br>" + myBook.publisher +                         "<br>Current page is " + myBook.pagenumber );         document.write("<br>Page forward: " ); 10      for(i=0;i<3;i++){ 11          document.write("<br>" +  myBook.uppage()  );             //  Move forward a page  }         document.write("<br>Page backward: ");         for(;i>0; i--){ 12          document.write("<br>" +  myBook.backpage()  );             //  Move back a page  }     </script>     </body>     </html> 

EXPLANATION

  1. This is the constructor function that is used to build the object by assigning it properties and methods. The parameter list contains the values for the properties title, author , and publisher .

  2. The this keyword refers to the book object. The book object is given a pagenumber property initalized to .

  3. A method is defined by assigning the function to a property of the book object. this.uppage is assigned the name of the function, pageForward , that will serve as the object's method. Note that only the name of the method is assigned to a property. There are no parentheses following the name. This is important. If you put parentheses here, you will receive an error message. When the method is called you use parentheses.

  4. The property this.downpage is assigned the name of the function, pageBackward , that will serve as the object's method.

  5. The function pageForward() is defined. Its purpose is to increase the page number of the book by one, and return the new page number.

  6. The function pageBackward() is defined. Its purpose is to decrease the page number by one and return the new page number.

  7. A new object called myBook is created. The new operator invokes the book() function with three arguments: the title of the book, the author, and the publisher.

  8. The pagenumber property is set to 5 .

  9. The properties of the object are displayed in the browser window.

  10. The for loop is entered. It will loop three times.

  11. The uppage() method is called for the myBook object. It will increase the page number by 1 and display the new value, each time through the for loop.

  12. The backpage() method is called for the myBook object. It will decrease the page number by 1 and display the new value, each time through the loop. The output is shown in Figure 8.7.

    Figure 8.7. Calling user-defined methods. Output from Example 8.6.

    graphics/08fig07.jpg

Properties Can Be Objects

In "Properties of the Object" on page 129 we said that any object subordinate to another object is also a property of that object; thus, if a parent object has objects below it in the hierarchy, those child objects are properties of their parent and separated from their parent with a dot. So how would you create subordinate objects? You create a subordinate object just as you create any other object ”with a constructor method. The one thing you must remember is that if the object being created is already a property of another object, you cannot use the var keyword preceding its name. For example, var pet.cat = new Object() will produce an error because cat is a property of the pet object and properties are never variables. (See Figure 8.1.) Weird, huh?

Example 8.7
 <html>     <head><title>Properties Can be Objects</title>         <script language = "javascript"> 1  var pet = new Object();  //  pet is an object  2  pet.cat = new Object();  //  cat is a property of the pet  //  object. cat is also an object  3  pet.cat.name="Sylvester";  //  cat is assigned properties  pet.cat.color="black"; 4  pet.dog = new Object();  pet.dog.breed = "Shepherd";             pet.dog.name = "Lassie";         </script>     </head>     <body bgcolor="lightblue">         <script language = "javascript"> 5           document.write("<b>The cat's name is " +  pet.cat.name  + "."); 6           document.write("<br>The dog's name is " +  pet.dog.name  + ".");         </script>     </body>     </html> 

Output:

 5   The cat's name is Sylvester. 6   The dog's name is Lassie. 

EXPLANATION

  1. A new pet object is created with the Object() constructor.

  2. The Object() constructor creates a cat object below the pet in the object hierarchy; that is, a cat object subordinate to the pet object and also a property of it. You cannot precede pet.cat with the keyword var because properties are never considered variables.

  3. The new object also has a property called name which is assigned a value, Sylvester .

  4. The Object() constructor creates an dog object below the pet in the object hierarchy; that is, a dog object subordinate to the pet object and also a property of it.

  5. The name property for the cat object is displayed.

  6. The name property for the dog object is displayed.

8.2.5 Object Literals

When an object is created by assigning it a comma-separated list of properties enclosed in curly braces, it is called an object literal. Each property consists of the property name followed by a colon and the property value. An object literal can be embedded directly in JavaScript code.

FORMAT

 
 var object = { property1: value, property2: value }; 

Example:

 
 var area = { length: 15, width: 5 }; 
Example 8.8
 <html>     <head><title>Object Literals</title>     </head>     <body bgcolor="yellow">         <script language = "javascript"> 1  var car = {  2  make: "Honda",   year: 2002,   price: "30,000",   owner: "Henry Lee",  3  };  4           var details=car.make + "<br>";             details += car.year + "<br>";             details += car.price + "<br>";             details += car.owner + "<br>";             document.write(details);         </script>     </body>     </html> 

EXPLANATION

  1. An object literal car is created and initialized .

  2. The properties for the car object are assigned. Properties are separated from their corresponding values with a colon and each property/value pair is separated by a comma.

  3. The object definition ends here.

  4. The variable called details is assigned the properties of the car object for display. The output is shown in Figure 8.8.

    Figure 8.8. Literal object properties. Output from Example 8.8.

    graphics/08fig08.jpg



JavaScript by Example
JavaScript by Example (2nd Edition)
ISBN: 0137054890
EAN: 2147483647
Year: 2003
Pages: 150
Authors: Ellie Quigley

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