jQuery in Action
324
APPENDIX
JavaScript that you need to know but might not!
A.1.3 Object literals
In the previous section, we created an object that modeled some of the properties
of a motorcycle, assigning it to a variable named
of a motorcycle, assigning it to a variable named
ride
. To do so, we used two
new
operations, an intermediary variable named
owner
, and a bunch of assignment
statements. This is tedious--as well as wordy and error-prone--and makes it dif-
ficult for us to visually grasp the structure of the object during a quick inspection
of the code.
ficult for us to visually grasp the structure of the object during a quick inspection
of the code.
Luckily, we can use a notation that's more compact and easier to visually scan.
Consider the following statement:
var ride = {
make: 'Yamaha',
model: 'V-Star Silverado 1100',
year: 2005,
purchased: new Date(2005,3,12),
owner: {
name: 'Spike Spiegel',
occupation: 'bounty hunter'
}
};
Using an object literal, this fragment creates the same
ride
object that we built up
with assignment statements in the previous section.
This notation, which has come to be termed
JSON
(JavaScript Object Nota-
tion
1
), is much preferred by most page authors over the multiple-assignment
means of object building. Its structure is simple; an object is denoted by a match-
ing pair of braces, within which properties are listed delimited by commas. Each
property is denoted by listing its name and value separated by a colon character.
ing pair of braces, within which properties are listed delimited by commas. Each
property is denoted by listing its name and value separated by a colon character.
NOTE
Technically,
JSON
has no means to express date values, primarily because
JavaScript itself lacks any kind of date literal. When used in script, the
Date
constructor is usually employed as shown in the previous example.
When used as an interchange format, dates are frequently expressed
either as a string containing the
either as a string containing the
ISO
8601 format or a number expressing
the date as the millisecond value returned by
Date.getTime()
.
As we can see by the declaration of the
owner
property, object declarations can
be nested.
1
For more information, you can visit http://www.json.org/.