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

Học JavaScript qua ví dụ part 23 potx

7 303 0

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

THÔNG TIN TÀI LIỆU

ptg 196 Chapter 8 • Objects 8.5 Extending Objects with Prototypes In object-oriented languages, like Java and C++, the object, along with its properties (state) and methods (behavior), is bundled up into a container called a class. These pro- gramming languages all allow classes to reuse and extend an existing class; that is, inherit commonly used state and behaviors from other classes. A new class, called a sub- class, can be derived from an existing class. For example, if you have a Pet class, let’s say all pets have an owner, a gender, and some methods for setting and getting the proper- ties. We could create subclasses of the Pet, such as a Dog and Cat, because both the Dog and Cat share the same properties as a Pet. The code for the Pet can be extended to the Dog and the Cat by using inheritance. Then each subclass can be refined further by add- ing its own specific features. Let’s look at an example of how JavaScript might use inheritance. A constructor func- tion called divStyle() has been defined. It will be used to create div containers to style a Web page. The constructor defines the properties for a div, for example, the borders, pad- ding, background color, and so on, and has a divGet() method to display the div in the document. Later we want to make divStyle objects but change or add properties; perhaps change the width of the border or set a border color. We can reuse or extend the divStyle code by using inheritance. Section 8.2 explained that unlike Java and C++, JavaScript doesn’t have a class mech- anism per se, but inheritance involves reusing or extending a class. With JavaScript we can simulate a class with a constructor function and the new keyword. And to imple- ment inheritance JavaScript extends a the class with a prototype. (For those of you who are Java or C++ programmers, JavaScript does not use keywords like extended, protected, private, public, etc.). How does prototype inheritance work? JavaScript functions are automatically given an empty prototype object. If the function acts as a constructor function for a class of objects, the prototype object can be used to extend the class. Each object created for the class is also given two properties, a constructor property and a prototype property. The constructor property is a reference to the function that created this object, and the prototype property a reference to its prototype object. This prop- erty allows the object to share properties and methods. Figure 8.12 The book object’s properties. From the Library of WoweBook.Com ptg 8.5 Extending Objects with Prototypes 197 Like any other object, you can assign properties and methods to the prototype object. You do this with the prototype property. When values are assigned to an object’s proto- type property, they are automatically extended to all instances of the class. After an object has been created, new properties and methods can be added to the prototype object, and any objects created after that will automatically inherit the new properties and methods. This is how JavaScript implements inheritance. It allows you to reuse code and customize an object. Let’s say we define a constructor function called Book() with a set of properties such as title and author. The Book() constructor function is JavaScript’s way of creating a class. The constructor function is called with the new keyword and creates an instance of the Book class, an object called book1, and then the constructor function is called again and creates another Book object called book2, and so on. Now, after creating book1, we add another property such as book1.publisher. This property affects book1, and only book1. The publisher property is not extended to book2. The property would have to be added separately to each Book object that needs it or by adding it to the Book’s prototype. Adding a new property without using the prototype property EXAMPLE 8.11 </html> <head><title>Object Properties</title> 1 <script type="text/javascript"> function Book(title, author){ this.title =title; this.author=author; } </script> </head> <body bgColor="#EOFFFF"> <big> <script> 2 var book1 = new Book("Kidnapped","R.L.Stevenson"); var book2 = new Book("Tale of Two Cities", "Charles Dickens") 3 book1.publisher="Penguin Books"; document.write(book1.title + " is published by "+ 4 book1.publisher + "<br />"); document.write(book2.title + " is published by " + 5 book2.publisher); //Doesn’t have this property </script> </big> </body> </html> EXPLANATION 1 The constructor function called Book will define the properties and methods for a Book class. The function takes two parameters. 2 Two new Book objects are created, book1 and book2. Continues From the Library of WoweBook.Com ptg 198 Chapter 8 • Objects 8.5.1 Adding Properties with the Prototype Property What if in the previous example book2 we want to add a publisher property so that it is extended to all instances of the Book class? All objects have a prototype property. We can use the Book’s prototype property to assign new properties to the Book class that will now be available to the Book class and any instances of the class; that is, all Book objects will have the new properties. In Example 8.12, we will add new properties to the Book class. 3 A new property, called publisher, is assigned to the book1 object. It is available for this instance of the object. 4 JavaScript retrieves and displays the value of the publisher for the book1 object. 5 The second book object does not have access to the publisher property. It is unde- fined (see Figure 8.13). Figure 8.13 Defining a new property for an object. EXAMPLE 8.12 <html> <head><title>Object Properties</title> <script type="text/javascript"> 1 function Book(title, author){ this.title =title; this.author=author; } </script> </head> <body bgColor="#EOFFFF"> <big> <script> 2 var book1 = new Book("Kidnapped","R.L.Stevenson"); var book2 = new Book("Tale of Two Cities", "Charles Dickens") 3 Book.prototype.publisher = "Penguin Books"; EXPLANATION ( CONTINUED) From the Library of WoweBook.Com ptg 8.5 Extending Objects with Prototypes 199 8.5.2 The Prototype Lookup Chain When the program tries to retrieve an object’s property, JavaScript first looks to see if the property was defined directly for that object; for example, does the Book object have a title property? Does the Book object have a author property? If so, JavaScript retrieves the property. If the property has not been defined, then JavaScript looks at the object’s prototype to see if the property is defined there. If it is not defined there, JavaScript will go up to the parent object. This process of going up the hierarchy, called the prototype document.write(book1.title + " is published by "+ 4 book1.publisher + "<br />"); document.write(book2.title + " is published by " + book2.publisher); </script> </big> </body> </html> EXPLANATION 1 The constructor function called Book will define the properties and methods for a Book class. The function takes two parameters. 2 Two new Book objects are created, book1 and book2. 3 The Book class has a prototype object. It is assigned a property called publisher. Now the publisher property and its value are available to all Book objects. 4 In the last example only book1 got the new property. Now both book1 and book2 have inherited the publisher property found in the Book’s prototype (see Figure 8.14). If you don’t want all books to be published by “Penguin Books” you could set the value of the publisher to “Unknown” as a default and change it later; for example, book2.publisher=“Viking Press” and the book2 object would get the value “Viking Press.” Figure 8.14 Using the prototype for inheritance. EXAMPLE 8.12 (CONTINUED) From the Library of WoweBook.Com ptg 200 Chapter 8 • Objects lookup chain, can continue until JavaScript reaches the top of the chain. You might recall that the top object is called the Object object and it too has a prototype. Example 8.13 uses the prototype for the Object object and the prototype for the Book object to create new properties. To retrieve a property for a Book object, JavaScript would look up the property in the following order: 1. The object itself 2. The Book.prototype 3. The Object.prototype First JavaScript starts with a Book object. If looking for the Book’s title and author, then there is no need to look further; if, on the other hand, we want to get the publisher or category, then JavaScript will go up the chain and look at the Book’s prototype, and finally, if not there, go to the top Object object and look there (see Figure 8.15). If the Object object has not defined the property, it is undefined. (Much of the information in this paragraph should be credited to a paper on objects written by Mike Koss at http://mckoss.com/jscript/object.htm.) Figure 8.15 JavaScript looks for the property with Example 8.13. Object function Book() Object.prototype.category Book.prototype.publisher Constructors Prototype Chain book1 book2 book1.author book2.author book1.title book2.title From the Library of WoweBook.Com ptg 8.5 Extending Objects with Prototypes 201 Using The Prototype Property EXAMPLE 8.13 <html> <head><title>Object Properties</title> <script type="text/javascript"> 1 function Book(title, author){ this.title =title; this.author=author; } </script> </head> <body bgColor="#EOFFFF"> <big> <script> 2 var book1 = new Book("Kidnapped","R.L.Stevenson"); var book2 = new Book("Tale of Two Cities", "Charles Dickens") 3 Object.prototype.category="Fiction"; 4 Book.prototype.publisher = "Penguin Books"; document.write(book1.title + " is published by "+ 5 book1.publisher + " and is in the " + book1.category + " category <br />"); document.write(book2.title + " is published by "+ book2.publisher + " and is in the " + book1.category + " category <br />"); </script> </script> </big> </body> </html> EXPLANATION 1 The constructor function called Book will define the properties and methods for a Book class. The function takes two parameters. 2 Two new Book objects are created, book1 and book2. 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. Note that on line 5, the book uses the category property. (This is just an example to show how the pro- totype property is used, not meant to be practical.) 4 The Book class has a prototype object. It is assigned a property. Now the publisher property and its value are available to all Book objects. 5 When JavaScript tries to retrieve the value of the category property, the property was not directly assigned in the constructor function. JavaScript checks to see if a Book prototype has been defined in the property. It has not. Going up the chain, the next level up is the Object object. It does have this prototype property. The val- ue is retrieved (see Figure 8.16). 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 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 . 8.2 explained that unlike Java and C++, JavaScript doesn’t have a class mech- anism per se, but inheritance involves reusing or extending a class. With JavaScript we can simulate a class with. the new keyword. And to imple- ment inheritance JavaScript extends a the class with a prototype. (For those of you who are Java or C++ programmers, JavaScript does not use keywords like extended,. property? Does the Book object have a author property? If so, JavaScript retrieves the property. If the property has not been defined, then JavaScript looks at the object’s prototype to see if the

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

Xem thêm: Học JavaScript qua ví dụ part 23 potx

TỪ KHÓA LIÊN QUAN

TÀI LIỆU CÙNG NGƯỜI DÙNG

  • Đang cập nhật ...

TÀI LIỆU LIÊN QUAN