Show Love to the Object Literal

A Javascript tip from Chris Heilmann, who reckons the object literal is "pretty close to sliced bread". Replace:

var commonSense=null;
var standardsCompliance="50%";
function init(){
  // code
}
function doStuff(){
  // code
}
function doMoreStuff(){
  // code
}
 

with the object literal form:

awesome={
  commonSense:null,
  standardsCompliance:"50%",
  init:function(){
    // code
  },
  doStuff:function(){
    // code
  },
  doMoreStuff:function(){
    // code
  }
}
 

He's noticed that newer tutorials are tending to use the object literal form, and that object literals are one of several techniques to avoid name clutter:

  • Dont use generic names in your scripts (which is a shame as init and validate does what it says on the tin)
  • Add a name to each of the functions like easyFameAndFortune_init and easyFameAndFortune_validate
  • Turn the functions into methods and the variables into parameters of an object

Some libraries go further and offer functions that have to be new()'d to form an object, but if you all you want is a separate namespace, a singleton object literal is a good way to go.

Wow free space!
Super hosting provider might be here!

Is it Google?