Object literals

Essentially, a bunch of related properties clumped in-between { }. For example,

var planet = { // beginning of an object literal
      id: 34,
      name: "Imtempesta Nox",
      faction: { // another object literal
        factionId: 2,
        name: "Nex",
        notification: function() {
          document.write("Nex alliance ... unite!");
      cities: [  // an array of object literals
        { locationId: 15, name: "Gladius" }, // an obj lit
        { locationId: 16, name: "Chalybs" }, // another obj lit
        { locationId: 17, name: "Ensis" }    // another obj lit

Note, the above is not a constructor. So you cannot call it as

var myPlanet = new planet();

Also, that object literal, after it came into existence as an object, was immediately attached to the var planet. So if you do the following

var p1 = planet;
var p2 = planet;

then both p1 and p2 will be pointing to the same object instance that planet was pointing to. You can see this with the following test

console.log("p1.name setting");
p1.name = "p1's name";
console.log("p1 name = " + p1.name);  // "p1's name"
console.log("p2 name = " + p2.name);  // "p1's name" !!!
console.log("planet name = " + planet.name); // "p1's name"

Some code snippets from Microsoft Virtual Academy’s great JavaScript introductory series.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s