|
Free Open Book
Sams Teach Yourself JavaScript in 24 Hours |
Introducing ObjectsIn the previous hour, you learned how to use variables to represent different kinds of data in JavaScript. JavaScript also supports objects, a more complex kind of variable that can store multiple data items and functions. Although a variable can have only one value at a time, an object can contain multiple values, as well as functions for working with the values. This allows you to group related data items and the functions that deal with them into a single object. In this hour, you'll learn how to define and use your own objects. You've already worked with some objects:
The syntax for working with all three types of objectsDOM objects, built-in objects, and custom objectsis the same, so even if you don't end up creating your own objects, you should have a good understanding of JavaScript's object terminology and syntax. Creating ObjectsWhen you created an array in the previous hour, you used the following JavaScript statement: scores = new Array(4); The new keyword tells the JavaScript interpreter to use a functionin this case, the built-in Array functionto create an object. You'll create a function for a custom object later in this hour. Object Properties and ValuesEach object has one or more propertiesessentially, variables that will be stored within the object. For example, in Hour 4, you learned that the location.href property gives you the URL of the current document. The href property is one of the properties of the location object in the DOM. You've also used the length property of String objects, as in the following example from the previous hour: test = "This is a test." document.write(test.length); Like variables, each object property has a value. To read a property's value, you simply include the object name and property name, separated by a period, in any expression, as in test.length previously. You can change a property's value using the = operator, just like a variable. The following example sends the browser to a new URL by changing the location.href property: location.href="http://www.jsworkshop.com/"; By the Way An object can also be a property of another object. This is referred to as a child object. Understanding MethodsAlong with properties, each object can have one or more methods. These are functions that work with the object's data. For example, the following JavaScript statement reloads the current document, as you learned in Hour 4: location.reload(); When you use reload(), you're using a method of the location object. Like normal functions, methods can accept arguments in parentheses, and can return values. |
Main Menu |
| 500 Juegos Gratis | 500 Giochi Gratis | 500 Jeux Gratuits | 500 Jogos Gratis | 500 Kostenlose Spiele |