The JavaScript Module Pattern – adding namespace

The Module Pattern has as added benefit of allowing you to add namespace to classes. The below extends the previous example to make the class COM.LEKKIMWORLD.ModuleAbc. Very cool in my eyes and reduces the chance for name collisions much like with Dojo classes.

// Create a COM namespace
var COM = (function() {
  return {};
}());

// Create a LEKKIMWORLD namespace
COM.LEKKIMWORLD = (function() {
  return {};
}());

// Add a class called ModuleAbc to the COM.LEKKIMWORLD namespace
COM.LEKKIMWORLD.ModuleAbc = (function(secret) {
  // the object we're incapsulating
  var OBJ = {};

  // private variables (these are truely private and
  // cannot be accessed from the outside)
  var secret = "my secret is: "

  // my property
  OBJ.myproperty = "my property value";

  // echo method
  OBJ.echo = function(v) {
    return "Echo: " + v;
  };

  // return the object
  return OBJ;

});