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;

});

Published by

lekkim

Positive, competent, out-spoken, frank and customer focused architect and developer with a strong foundation in web, cloud and product development. I'm a strong advocate for API first and cloud based solutions and development. I have a knack for being able to communicate and present technically complicated matters in conference, customer and training settings. I've previously acted as team member and leader in a product organisation.