1. Trang chủ
  2. » Công Nghệ Thông Tin

Học JavaScript qua ví dụ part 24 pot

11 378 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 11
Dung lượng 852,28 KB

Nội dung

ptg 202 Chapter 8 • Objects 8.5.3 Adding Methods with Prototype JavaScript methods are just properties that have been assigned functions for their values. A common use for prototypes is to extend a class by giving it new methods. You can use a prototype to assign methods that are common to all objects in a given class. The benefit of using the prototype is that the method does not have to be created and initialized every time an object is created, and there is no duplication of function code. All objects in the class share the same prototype method. In Example 8.14, a new method is defined for the Book class to add a tax to the price of each book. All Book objects will have access to this method. Figure 8.16 Going up the prototype chain. EXAMPLE 8.14 <html> <head><title>Method Inheritance</title> <script type = "text/javascript"> 1 function Book(title, author, price){ // The Book constructor this.title = title; // Book properties/attributes this.author = author; this.price=price; 2 this.show=showProps; // Book method } 3 function showProps(){ var result = ""; for (var i in this){ result += i + " = " + this[i] + "<br />"; } return result; } </script> </head> <body> <script type="text/javascript"> // Add a new method with prototype From the Library of WoweBook.Com ptg 8.5 Extending Objects with Prototypes 203 4 Book.prototype.addTax=function addTax(){ this.price *= 1.18; return(this.price.toFixed(2)); } 5 var famousBook=new Book("War and Peace","Leo Tolstoy", 30.00); var myBook=new Book("JavaScript by Example", "Ellie Quigley", 25); 6 document.write("<br /><b>" + famousBook.show()+"<br />"); document.write("<br /><b>" + myBook.show()+"<br />"); 7 document.write("With tax \""+ famousBook.title +"\" costs $"+ famousBook.addTax() +".<br />"); document.write("With tax \""+ myBook.title + "\" costs $" + 8 myBook.addTax() +".<br />"); </script> </body> </html> EXPLANATION 1 The constructor function called Book defines the properties and methods for a Book class. (Book is a JavaScript representation of a class.) The constructor func- tion has a prototype object containing those properties that are inherited by all Book objects. 2 A function called showProps is defined on line 3. Its name is assigned to the prop- erty called show, making it a method for the Book class. 3 The function showProps uses the special for loop to iterate through all the proper- ties of an object. 4 The Book’s prototype property is used to add a function called addTax(). It calcu- lates and returns the price of the book with an 18 percent sales tax added. This function will be added as a method to the Book class and available to all objects in that class. JavaScript creates only one copy of the function and all book objects will point to that copy. 5 A new Book object, called myBook, is created. It has inherited all of the original properties of the Book class, including the new method defined by the prototype property, called addTax. 6 The show() method is called for the object, famousBook. The entire object, prop- erties and methods are displayed. You can see that addTax has been included. 7 The new method, addTax() is called for the object famousBook. 8 Again, addTax() is called for the object myBook. The result is shown in Figure 8.17. EXAMPLE 8.14 From the Library of WoweBook.Com ptg 204 Chapter 8 • Objects 8.5.4 Properties and Methods of All Objects As we have seen, all user-defined objects and built-in objects are descendants of the object called Object. The Object object has its own properties and methods that can be accessed by any objects derived from it. All objects have the properties and methods shown in Tables 8.1 and 8.2. Figure 8.17 Adding a new method with a prototype. Table 8.1 Object Properties Property What It Provides constructor A reference to the function that created the object. prototype A reference to the object prototype for the object. This allows the object to share properties and methods. Table 8.2 Some Object Methods Method What It Does toString() Returns a string representing a specified object. valueOf() Returns a primitive value for a specified object. From the Library of WoweBook.Com ptg 8.5 Extending Objects with Prototypes 205 You can also use the instanceof operator to test if the specified object is of the specified object type. If it is, true is returned. hasOwnProperty(property) Returns true if the specified property belongs to this object, not inherited from its prototype object chain. isPrototypeOf(object) Returns true if this object is one of the parent prototype objects of the specified child object. FORMAT var isInstance = objectName instanceof objectType; EXAMPLE var str1 = new String("good morning");// Create a new string object var result = sr1 instanceof String; if( result == true ){ } EXAMPLE 8.15 <html> <head><title>Object object</title> <script type="text/javascript"> 1 function Book(title, author){ this.title =title; this.author=author; } </script> </head> <body bgColor="#EOFFFF"> <big> <script> 2 Book.prototype.publisher="Oxford Press"; 3 Object.prototype.category="Fiction"; 4 var tale = new Book("Kidnapped","R.L.Stevenson"); 5 document.write("The value of Object's category property is "+ Object.prototype.category +"<br />"); 6 if(tale.constructor == Book){ document.write("tale is a Book object<br />"); document.write("The Book's constructor is defined as: "+ 7 tale.constructor + "<br />"); } Continues Table 8.2 Some Object Methods (continued) Method What It Does From the Library of WoweBook.Com ptg 206 Chapter 8 • Objects 8 if(tale.hasOwnProperty("author")){ document.write("The object has an author property.<br />"); } 9 if(Book.prototype.isPrototypeOf(tale)){ document.write("Book is a prototype of object tale.<br />"); } 10 if(tale instanceof Book){ document.write("tale is an instance of Book.<br />"); } 11 if(tale instanceof Object){ document.write("tale is an instance of Object.<br />"); } </script> </big> </body> </html> EXPLANATION 1 The constructor function called Book defines the properties and methods for a Book class. 2 The Book class starts with an empty prototype object. Now we assign it a property. The publisher property and its value are available to all Book objects. 3 By assigning a property to the Object object’s prototype, all instances of the Book class (or any class) will have access to the category property. 4 A new instance of the Book class is created, a reference to an object called tale. 5 The value of the Object object’s prototype property, category, is displayed. 6 The constructor property is inherited from the Object object and can be used with any of its descendants. This line tests if this object has a constructor. It does, so the block is entered. 7 The value assigned to the constructor property is the constructor function and the names of all of its arguments and properties. 8 The hasOwnProperty() method returns true if the property (its argument) belongs to the object being tested; in this case the object is tale and the method is checking to see if the author property belongs to it and is not inherited from the prototype chain. 9 Next we test to see if the tale object is inheriting from the Book class; that is, Book is a prototype for the tale class. 10 The instanceof operator returns true if the specified object, tale, is of the specified object type; that is, tale is a Book type. 11 The instanceof operator returns true if the specified object, tale, is of the specified object type; that is, tale is also an Object type. The output is shown in Figure 8.18. EXAMPLE 8.15 (CONTINUED) From the Library of WoweBook.Com ptg 8.5 Extending Objects with Prototypes 207 8.5.5 Creating Subclasses and Inheritance In the previous examples, we used the prototype object to extend properties and methods for a given class. In the next chapter you will see how to use prototyping to customize JavaScript’s built-in objects such as Date and String. Now, to demonstrate how inheritance works, we will define a base class called Pet, which will have its own properties and methods and can create instances via the “new” operator. Then we will use this base class to create two additional subclasses called Cat and Dog. Each of these subclasses (derived classes) will use the prototype property to inherit the properties and methods of the Pet class (see Figure 8.19). Both the Cat and the Dog class will be customized to have their own speak() method. Even though the name of the method is the same for both the Cat and Dog class, JavaScript will call the speak() method for the object to which it belongs; that is, when the speak() method is called for a Cat object, it will return “Meow”, and when called for a Dog object, it will say “Woof”. See Example 8.15 for the program code. Figure 8.18 Testing objects. Figure 8.19 A hierarchical tree-like structure used to describe base class and derived classes. Cat Dog Pet Object From the Library of WoweBook.Com ptg 208 Chapter 8 • Objects EXAMPLE 8.16 <html> <head><title>Creating a subclass</title> <script type="text/javascript"> 1 function Pet(){ // Base Class 2 var owner = "Mrs. Jones"; var gender = undefined; 3 this.setOwner = function(who) { owner=who;}; this.getOwner = function(){ return owner; } 4 this.setGender = function(sex) { gender=sex; } this.getGender = function(){ return gender; } } 5 function Cat(){} //subclass constructor 6 Cat.prototype = new Pet(); 7 Cat.prototype.constructor=Cat; 8 Cat.prototype.speak=function speak(){ return("Meow"); }; 9 function Dog(){};//subclass constructor 10 Dog.prototype= new Pet(); Dog.prototype.constructor=Dog; Dog.prototype.speak = function speak(){ return("Woof"); }; </script> </head> <body><big> <script> 11 var cat = new Cat; var dog = new Dog; 12 cat.setOwner("John Doe"); cat.setGender("Female"); 13 dog.setGender("Male"); 14 document.write("The cat is a "+ cat.getGender()+ " owned by " + cat.getOwner() +" and it says " + cat.speak()); document.write("<br>The dog is a "+ dog.getGender() +""+ " owned by " + dog.getOwner() + " and it says " + dog.speak()); </script> </big> </body> </html> EXPLANATION 1 The constructor function called Pet will define the properties and methods for a Pet class. The Pet constructor creates a class of Pets and is the base class for the Dog and Cat classes defined later in the program. 2 Local variables are set for the object. All Pet objects will have an owner and a gen- der. The default value for the owner is Mrs. Jones. The gender is undefined. From the Library of WoweBook.Com ptg 8.5 Extending Objects with Prototypes 209 3 The setOwner and getOwner methods are defined for the Pet. All Pet objects will have access to these methods. 4 The setGender and getGender methods are defined for the Pet. 5 An empty function called Cat is declared. It will be used as the constructor func- tion for a Cat class. 6 By creating a new Pet object and assigning it to the Cat’s prototype, all properties and methods of the Pet will now be available to the Cat. This is how JavaScript implements inheritance. 7 The constructor property returns a reference to the function that initialized the ob- ject; in this case, the Pet. (The value of this property is a reference to the function itself, not a string containing the function’s name). By updating the constructor property, it will contain a reference to the new Cat class constructor, not its parent, the Pet. Now the Cat constructor is the constructor for all Cat objects. 8 We are creating a new method for the Cat, called speak. It will be a property of the Cat’s prototype. All cat objects will have access to this method and all cats will speak “Meow”. 9 An empty function, called Dog, is created. 10 By creating a new Pet object and assigning it to the Dog’s prototype, all properties and methods of the Pet will now be available to the Dog. The Dog inherits from the Pet. The constructor property is also updated so that it will reference the Dog class. The Dog will also have a speak() method. How does JavaScript know which speak() method to call? The object that calls this speak method has its own copy of it. 11 A new object called cat is instantiated. And in the next line, a dog object is instan- tiated. They both inherit from the Pet class. 12 The cat object calls the setOwner() method with a new value. It inherited this method from the Pet. 13 The dog calls the setGender() method, inherited from the Pet. 14 Using the getOwner() and getGender() and speak() methods, we display the prop- erties of the cat object and the dog object. The output is shown in Figure 8.20. Figure 8.20 Subclasses and their properties. EXPLANATION ( CONTINUED) From the Library of WoweBook.Com ptg 210 Chapter 8 • Objects 8.6 What You Should Know Because JavaScript is based on all kinds of objects such as windows, documents, input devices, buttons, and so on, in this chapter we talked about what objects are and how they are used. The purpose of creating your own objects before talking about JavaScript’s core objects and DOM objects is to give you an understanding of the terminology and syntax and how objects relate to each other in an object model. Now you should understand: 1. Why an object is a composite type. 2. Several ways to create an object. 3. How to use an object constructor. 4. The difference between properties and methods. 5. The difference between a method and a function. 6. How a function can act as a constructor. 7. What the this keyword is used for. 8. How to create an object literal. 9. How to use the with keyword. 10. How to extend an object with its prototype. From the Library of WoweBook.Com ptg 8.6 What You Should Know 211 1. Create a circle object with the Object() constructor and a method that will cal- culate its circumference. 2. Write a function that will create a clock object. a. It will have three properties: seconds, minutes, and hours. b. Write two methods: setTime() to set the current time and displayTime() to display the time. c. The user will be prompted to select either a.m./p.m., or military time. The value he or she chooses will be passed as an argument to the displayTime() method. 3. The output will be either 14:10:26 or 2:10:26 pm depending on what argument was passed to the display() method. 4. The following function acts as a constructor to create an Employee object. Use this function to create three new employees. Set the properties and print the employees’ names. Add a phone property to this function. <script type="text/javascript"> function Employee(){ var = name; this.getName = function(){ return this.name; } this.setName = function(name){ this.name = name; }; } 5. Create an object literal called Customer. The Customer will have properties: a name, gender, photo, and occupation. There will be one method called showCustomer(). The user will be prompted for each of the property val- ues. Use the showCustomer() method to display the data in an HTML table. 6. Using JavaScript prototyping, extend the Employee (Exercise 4). Create two new subclasses from the Employee: a Salesman and a Manager class. Use a pro- totype to create a salary property for the new employees (setSalary, getSalary), and a setRaise() method to add 15 percent to the salary. Check to see if each of the new Employees is an instance of the Employee class. Exercises Exercises From the Library of WoweBook.Com . ptg 202 Chapter 8 • Objects 8.5.3 Adding Methods with Prototype JavaScript methods are just properties that have been assigned functions for their values. A common. 8.14 <html> <head><title>Method Inheritance</title> <script type = "text /javascript& quot;> 1 function Book(title, author, price){ // The Book constructor this.title. />"; } return result; } </script> </head> <body> <script type="text /javascript& quot;> // Add a new method with prototype From the Library of WoweBook.Com ptg 8.5

Ngày đăng: 04/07/2014, 02:20

TỪ KHÓA LIÊN QUAN