HTML and CSS Reference
In-Depth Information
Figure 8.7 Two objects of the Distance class call the calculate() method.
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
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.)
1. Firefox will not complain if the last field is terminated with a comma; Internet Explorer will raise an
Search WWH ::

Custom Search