ptg 182 Chapter 8 • Objects 8.2 Classes and User-Defined Functions 8.2.1 What Is a Class? JavaScript ain’t got no class! If you are familiar with Java or C++ you may be wondering how to create a class in JavaScript. A class is a template or blueprint that describes the properties and behavior of all objects that belong to that specific class, so you may have a Car class or a House class or a Widget class. A Car class would be defined with the properties and methods for a Car and then you could create as many Car objects as you want using the class as a template. But JavaScript doesn’t have classes in the traditional sense. It doesn’t have a class keyword. We must develop the notion of classes in a differ- ent way. A new JavaScript class is defined by creating a simple function. The name of the function will serve as the class name for an object, and the function will define its prop- erties and methods; it serves as a blueprint or prototype of the object. When the function is called with the new keyword, it acts as a constructor; that is, it builds the new object and then returns a reference to it. We can say that if you call the Book() constructor func- tion, it returns a reference to a new Book object, an instance of the Book class. 8.2.2 What Is this? Internally, JavaScript creates an object, and then calls the constructor function. Inside the constructor, the variable this is initialized to point to this newly created object. The this keyword is a sort of shorthand reference that keeps track of the current object. When a function is used as a constructor, the this keyword is used to set the properties for the object that was just created. In this way you can create as many objects as you need and JavaScript this will refer to the current object. In Example 8.4, a function is used to create a Book class with two properties, a title and an author. The this keyword refers to the current Book object. Methods can be assigned to an object in the constructor function so that the method can be applied to multiple instances of an object. In Example 8.5, two methods are cre- ated in the Book constructor function called uppage() and backpage(). Any Book object has access to these methods. Figure 8.4 An object and its properties. From the Library of WoweBook.Com ptg 8.2 Classes and User-Defined Functions 183 EXAMPLE 8.4 <script type="text/javascript"> 1 function Book(){ // Create a Book class 2 this.title = "The White Tiger"; // Properties this.author = "Aravind Adiga"; } 3 var bookObj = new Book; // Create new Book object alert(bookObj.title + " by " + bookObj.author); </script> EXPLANATION 1 The Book() function defines a class. When called with the new keyword, the func- tion acts as a constructor function. 2 The properties describe the characteristics or attributes of the object. The this key- word is a reference to the current object. The title and author are defined for this book object. 3 A new Book object is created and a reference to it assigned to the variable bookObj. The new keyword, used with the Book() function, causes the function to behave as a constructor. You can create as many book objects as you want, but in this exam- ple, they would all have the same title and author. See Figure 8.5 for the output. Figure 8.5 An instance of the Book class. EXAMPLE 8.5 <html> <head><title>User-defined objects</title> <script type ="text/javascript"> 1 function Book(title, author, publisher){ // Receiving // parameters 2 this.pagenumber=0; // Properties this.title = title; this.author = author; this.publisher = publisher; 3 this.uppage = pageForward; // Create methods 4 this.backpage = pageBackward; } Continues From the Library of WoweBook.Com ptg 184 Chapter 8 • Objects 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> <script type = "text/javascript"> 7 var myBook = new Book("JavaScript by Example", "Ellie Quigley", "Prentice Hall" ); // Create new object 8 myBook.pagenumber=5;//Assign a page number 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 will represent a class called “Book”. The function creates the object and assigns it properties and methods. The parameter list contains the values for the properties title, author, and publisher. Each time this function is called a new Book class is instantiated. 2 The this keyword refers to the Book object. The Book object is given a pagenumber property initialized to 0. 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 prop- erty, i.e., a reference to the function’s definition. There are no parentheses follow- ing the name. This is important. If you put parentheses here, you will receive an error message. But when the method is called you must use parentheses. EXAMPLE 8.5 (CONTINUED) From the Library of WoweBook.Com ptg 8.2 Classes and User-Defined Functions 185 8.2.3 Inline Functions as Methods Rather than naming a function outside the class, an inline or anonymous function can be assigned directly to a property within the constructor function. (Every instance of the 4 The property this.backpage 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 num- ber by one and return the new page number. 7 A new object called myBook is created. The new operator invokes the Book() con- structor 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.6. Figure 8.6 An instance of the Book class, its properties, and methods. EXPLANATION ( CONTINUED) From the Library of WoweBook.Com ptg 186 Chapter 8 • Objects class will have a copy of the function code.) In Example 8.6, the calculate property is assigned an inline or anonymous function. Because it is part of the definition of the Dis- tance() constructor, only objects of the Distance class will have access to the method, thereby encapsulating the method. In previous examples the functions that served as methods were defined outside of the constructor, making available to any class. EXAMPLE 8.6 <html> <head><title>functions</title> <script type="text/javascript"> 1 function Distance(r, t){//Constructor function 2 this.rate = r; this.time = t; 3 this.calculate=function() { return r * t; } // anonymous } </script> </head> <body> <script type ="text/javascript"> 4 var trip1 = new Distance(50, 1.5); 5 var trip2 = new Distance(75, 3.2); 6 alert("trip 1 distance: "+ trip1.calculate()); alert("trip 2 distance: "+ trip2.calculate()); </script> </body> </html> EXPLANATION 1 This is the constructor function for the Distance class. It takes two parameters, r and t, and returns a reference to an object. 2 Properties are assigned to the object. The this keyword is a reference to the current object. 3 When a function is assigned to a property, it is called a method. This is an inline or anonymous function. It has no name but has been defined and assigned to the object as a method. 4 A new object called trip1 is created with the new constructor. Two arguments are passed, the rate (how fast) and the time (in hours). This is the first instance of the Distance class. 5 Another object, trip2, is created and sends different argument values. 6 See Figure 8.7. The method called calculate() is invoked for each object. The alert box displays the value returned from the calculate() method; that is, the distance traveled. From the Library of WoweBook.Com ptg 8.3 Object Literals 187 8.3 Object Literals Object literals enable you to create objects that support many features without directly invoking a function. When a function acts as constructor you have to keep track of the order of arguments that will be passed, and so on. Not so with object literals. They are similar to hashes in other languages using key/value pairs to represent fields. The fields can be nested. The basic syntax for an object literal is: 1. A colon separates the property name from its value. 2. A comma separates each set of name/value pairs from the next set. 3. The comma should be omitted from the last name/value pair. 1 Even with nested key/value pairs, the last key/value pair does not have a comma. 4. The entire object is enclosed in curly braces. The value assigned to a property can be of any data type, including array literals and object literals (arrays are covered in Chapter 9). Using the new operator with the Object() constructor or an object literal is both simple and logical, but the biggest short- coming is that the code is not reusable; that is, you would have to retype the code to use it again within the program, whereas you can use a constructor function to create mul- tiple instances of an object. In Example 8.7, one soldier object is created as an object literal, but we cannot create two soldier objects unless we redefine another entirely new object. (See JSON in Chapter 18, “An Introduction to Ajax (with JSON),” for a good rea- son to use object literals.) Figure 8.7 Two objects of the Distance class call the calculate() method. 1. Firefox will not complain if the last field is terminated with a comma; Internet Explorer will raise an exception. From the Library of WoweBook.Com . User-Defined Functions 8.2.1 What Is a Class? JavaScript ain’t got no class! If you are familiar with Java or C++ you may be wondering how to create a class in JavaScript. A class is a template or blueprint. a template. But JavaScript doesn’t have classes in the traditional sense. It doesn’t have a class keyword. We must develop the notion of classes in a differ- ent way. A new JavaScript class. </script> </head> <body> <script type = "text /javascript& quot;> 7 var myBook = new Book(" ;JavaScript by Example", "Ellie Quigley", "Prentice