When used well, this can reduce object initialization time and memory consumption.
/*
The quotes around a property's name in an
object literal are optional if the name would be
a legal JavaScript name and not a reserved word
*/
var stooge={
name:"hebian",
"no.":"001"
};
//alert(stooge["name"]);
//alert(stooge["no."]);
/*Objects can nest*/
var flight = {
airline: "spring",
number: 123,
departure:{
time:"09-22 14:55",
city:"shanghai"
}
};
//alert(flight["airline"]);
//alert(flight.airline);
//alert(flight.departure.time);
/*
The || operator can be used to fill in default values:
*/
//alert(flight.arrival || "unknown");
/*
Attempting to retrieve values from undefined will throw a TypeError exception.
This can be guarded against with the && operator:
*/
//alert(flight.arrival && flight.arrival.time);
/*
If the property name already exists in the object, the
property value is replaced:
*/
flight.number += 1;
//alert(flight.number);
/*
If the object does not already have that property name, the object is augmented:
*/
flight.arrival = {
time:"09-22 19:55",
city:"changsha"
};
alert(flight.arrival.city);
/*
Objects are passed around by reference. They are never copied:
*/
var x = stooge;
x.nickname = 'Curly';
var nick = stooge.nickname;
// nick is 'Curly' because x and stooge
// are references to the same object
var a = {}, b = {}, c = {};
// a, b, and c each refer to a
// different empty object
a = b = c = {};
// a, b, and c all refer to
// the same empty object