Học JavaScript qua ví dụ part 20 pps

8 262 0
Học JavaScript qua ví dụ part 20 pps

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

Thông tin tài liệu

ptg 175 chapter 8 Objects 8.1 What Are Objects? JavaScript is all about objects. Windows and buttons, forms and images, links and anchors are all objects. Programming languages like Java, C++, and Python that focus on objects are called object-oriented programming (OOP) languages. JavaScript is called an object-based language because it doesn’t technically meet the criteria of the more heavy-duty languages, but it certainly behaves as an object-oriented language. Some people are apprehensive at the thought of tackling this kind of programming, although the mystique is somewhat diminished from what it was back in the last century when the top-down procedural approach to programming was more in vogue. In the real world, you may see a book or a cup or a hat as an object. JavaScript can represent data such as a string or a number as an object, and JavaScript lets you create your own objects. When talking about JavaScript data types in Chapter 3, “The Building Blocks: Data Types, Literals, and Variables,” we discussed two types: primitive and composite. Objects are composite types. They provide a way to organize a collection of data into a single unit. Object-oriented languages, such as C++ and Java, bundle up data and behav- ior and call it an object. So does JavaScript. When you learn about objects, they are usually compared to real-world things, like a cat, a book, or a triangle. Using the English language to describe an object, the object itself would be like a noun. Nouns are described with adjectives. A cat might be described as fat, furry, smart, or lazy. The book is old, with 400 pages, and contains poems. The triangle has three sides, three angles, and red lines. The adjectives that collectively describe these objects are called properties or attributes. The object is made up of a collection of these properties or attributes. In English, verbs are used to describe what the object can do or what can be done to it. The cat eats, sleeps, and meows. The book is read, its pages can be turned forward and backward, and it can be opened or closed by the reader. The triangle’s sides and angles can be increased and decreased, it can be moved, and it can be colored. These From the Library of WoweBook.Com ptg 176 Chapter 8 • Objects verbs are called methods in object-oriented languages. JavaScript sees your browser window as an object, a window that can be resized, opened, closed, and so on. It sees all the frames, documents, images, and widgets inside the window as objects. And these objects have properties and methods. JavaScript supports several types of objects, as follows: 1. User-defined objects defined by the programmer. 2. Core or built-in objects, such as Date, String, and Number (see Chapter 9, “JavaScript Core Objects”). 3. Browser objects, the BOM (see Chapter 10, “It’s the BOM! Browser Objects”). 4. The Document objects, the DOM (see Chapter 15, “The W3C DOM and Java- Script”). This chapter focuses on user-defined objects, objects that you will create and manipu- late. Once you understand the syntax and how these objects work, JavaScript’s core objects will be much easier to understand and use. 8.1.1 Objects and the Dot Syntax An object model is a hierarchical tree-like structure used to describe all of the compo- nents of an object (see Figure 8.1). For example, in Chapter 1, “Introduction to Java- Script,” we discussed the DOM (see more in Chapter 15), a tree-like structure that represents an HTML document and all of its elements, and this tree-like model is also used to represent the browser and its components (BOM; see Chapter 10). JavaScript objects and user-defined objects use this same model. When accessing an object in the tree, the object at the top of the tree is the root or parent of all parents. If there is an object below the parent it is called the child, and if the object is on the same level, it is a sibling. A child can also have children. A dot (.) is used to separate the objects when descending the tree; for example, a parent is separated from its child with a dot. In the following example, the Object object is the primitive JavaScript object from which all other objects are derived and the Object object has its own properties and methods that all objects will have access to. (We list these properties and methods in Tables 8.1 and 8.2.) The cat object and the dog object are derived from the Object object. To get the cat’s name, you would say cat.name, and to get the dog’s breed you would say dog.breed. The Object object is not named when going down in the hierarchy. Figure 8.1 A hierarchical tree-like structure used to describe components of an object. name color size attitude name color breed Cat Dog Object From the Library of WoweBook.Com ptg 8.1 What Are Objects? 177 8.1.2 Creating an Object with a Constructor JavaScript allows you to create an object in a number of ways. One way is with a con- structor. A constructor is a special kind of function that creates the blueprint for an object. The new keyword precedes the name of the constructor that will be used to create the object. By convention, constructor names start with a capital letter to distinguish them from ordinary functions. var myNewObject = new Object(argument, argument, ) To create the cat object, for example, you could say: var cat = new Object(); 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 name of a function. The new oper- ator treats the function as a constructor. This function may be a JavaScript constructor or one that is user-defined. JavaScript comes with several built-in constructors, such as Object(), Array(), Date(), and RegExp(). With them you use the new operator followed by the constructor function and any arguments it takes. A reference to the object is returned and assigned to a variable. var car = new Object(); var friends = new Array("Tom", "Dick", "Harry"); var holiday = new Date("July 4, 2011"); var rexp = new RegExp("^[a-zA-Z]"); The Object() Constructor. JavaScript provides a special predefined constructor function called Object(), used with the new keyword, to build a generic object. The return value of the Object() constructor is assigned to a variable. The variable contains a reference to an instance of a new object. See Example 8.1. Later we will create a user- defined function that will act as a constructor. FORMAT var myobj = new Object(); EXAMPLE 8.1 <html> <head><title>The Object() Constructor</title> <script type = "text/javascript"> 1 var cat = new Object(); 2 alert(cat); </script> </head> <body></body> </html> From the Library of WoweBook.Com ptg 178 Chapter 8 • Objects 8.1.3 Properties of the Object Properties describe the object. The object name is followed by a dot and a property. The properties are accessible only via their object. In Figure 8.3, the top object is the Object object. If we create a new cat and a dog object, as shown in Example 8.2, they are descen- dants of the Object object. Although the dog and the cat are objects in their own right, they are considered properties of the Object object. In fact, any object subordinate to another object is also a property of that object. The cat and the dog are descendants of the Object object. They also have properties that describe them, such as name, color, size, and so forth. The Object object is not listed in the hierarchy when using the dot syntax. To assign properties to the cat object, the syntax would be as follows: cat.name = "Sneaky"; cat.color="yellow"; In Example 8.2 a new object is created with the new keyword and the Object() construc- tor. Properties are assigned to the object and their values retrieved. EXPLANATION 1 The Object() constructor creates and returns a reference to a cat object. 2 The returned value from the Object() constructor is a reference to an object, as shown in the Figure 8.2. [object Object] means that the cat is a descendant of the Object object from which all objects are derived. Figure 8.2 cat is an object. EXAMPLE 8.2 <html> <head><title>User-defined objects</title> 1 <script type = "text/javascript"> 2 var toy = new Object(); // Create an instance of the object 3 toy.name = "Lego"; // Assign properties to the object toy.color = "red"; toy.shape = "rectangle"; 4 </script> </head> <body bgcolor="lightblue"> From the Library of WoweBook.Com ptg 8.1 What Are Objects? 179 In JavaScript you might see the syntax: window.document.bgColor = "lightblue"; The window is the top object in the Browser Object Model. It is the parent of all par- ents; the document is an object but, because it is subordinate to the window, it is also a property of the window object. Although the background color, bgColor, is a property of the document object, by itself it is not an object. (It is like an adjective because it describes the document.) window document bgColor 5 <script type = "text/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 starts 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. (All objects are descendants of the Object object.) 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 ob- ject’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. EXAMPLE 8.2 (CONTINUED) From the Library of WoweBook.Com ptg 180 Chapter 8 • Objects 8.1.4 Methods of the Object Methods are special functions that object-oriented languages use to describe the object’s behavior. Methods are attached to the object with a dot and are only accessible via that object. Methods, like verbs, are action words that perform some operation on the object. The cat purrs and the dog barks. The cat object may have a method called sleep() or play() and the dog object may have a method called sit() or stay(), and both of them could have a method called eat(). The dot syntax is used to call the methods just as it was used to separate objects from their properties. When invoked, a set of parentheses are postfixed to the name of the method. Omitting the parentheses when using a method results in an error. cat.play(); Methods, like functions, can take arguments, messages that will be sent to the object: dog.fetch("ball"); A JavaScript example: window.close(); document.write("Hello\n"); Example 8.3 demonstrates how to create an object and assign properties. But we need to complete the definition of an object by assigning methods to it. Instead of assigning a value such as a string or number to the property of an object, you assign a function to it. Methods let the object do something or let something be done to it. There is little dif- ference between a function (see Chapter 7, “Functions”) and a method, except that a function is a stand-alone unit of statements and a method is attached to an object, is accessed only via the object, and can be referenced by the this keyword. Like functions, methods also take arguments and can return a value. EXAMPLE 8.3 <html> <head><title>User-defined objects</title> <script type= "text/javascript"> 1 var toy = new Object(); // Create the object 2 toy.name = "Lego"; // Assign properties to the object toy.color = "red"; toy.shape = "rectangle"; 3 toy.display=printObject; // Function name is assigned as a // property of the object 4 function printObject(){ document.write("<b>The toy is a " + toy.name + ".<br>"); From the Library of WoweBook.Com ptg 8.1 What Are Objects? 181 document.write("It is a " + toy.color + " " + toy.shape + ".<br />"); } </script> </head> <body> <script type = "text/javascript"> 5 toy.display(); //Object method is called 6 toy.color="blue"; 7 toy.display(); </script> </body> </html> EXPLANATION 1 The Object() constructor is called with the new keyword to create an instance of a new object. A reference to the new object is assigned to the variable, toy. We now have a toy object. 2 The properties describe the characteristics or attributes of the object. Properties act as variables for the object, but do not use the var keyword. The toy object’s name property is assigned “Lego”, its color property is assigned “red”, and its shape property is assigned “rectangle”. The display property is assigned the name of a function. 3 When the name of a function is assigned to a property, the property will serve as a method for the object. The name of a function, printObject, is assigned to the display property. Lines 5 and 7 demonstrate how to invoke the new method dis- play(). 4 printObject() function is defined. It will be used as a method for the toy object, allowing the toy object to display its properties. Instead of display, we could use the same name for this property; that is, toy.printObject = printObject. By giving the property a different name, in this case, display, it is clear that the property is being assigned a function name and that the object’s method name is display, not print- Object. 5 The object’s display() method is called. Its function is to print the color and shape properties of the toy object. 6 The global object called toy is available within the script. The value of the toy ob- ject’s color property is changed. 7 The object’s display() method is called again showing that the value of the color property has been changed to “blue”. The result is shown in Figure 8.4. EXAMPLE 8.3 (CONTINUED) From the Library of WoweBook.Com 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 . cup or a hat as an object. JavaScript can represent data such as a string or a number as an object, and JavaScript lets you create your own objects. When talking about JavaScript data types in. methods. JavaScript supports several types of objects, as follows: 1. User-defined objects defined by the programmer. 2. Core or built-in objects, such as Date, String, and Number (see Chapter 9, JavaScript. oper- ator treats the function as a constructor. This function may be a JavaScript constructor or one that is user-defined. JavaScript comes with several built-in constructors, such as Object(),

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

Từ khóa liên quan

Tài liệu cùng người dùng

Tài liệu liên quan