8.2 User -Defined ObjectsAll user-defined objects and built-in objects are descendants of an object called Object . 8.2.1 The new OperatorThe 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() ConstructorA 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
8.2.3 Creating the Object with a User-Defined FunctionTo 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
8.2.4 Defining Methods for an ObjectThe 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
A Method Defined in a ConstructorMethods 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
Properties Can Be ObjectsIn "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
8.2.5 Object LiteralsWhen 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
|