Return to Snippet

Revision: 58726
at July 30, 2012 22:30 by timsommer


Initial Code
var basketModule = (function () {
  var basket = []; //private
  function doSomethingPrivate() {
    //...
  }
  function doSomethingElsePrivate() {
    //...
  }
  return { //exposed to public
    addItem: function (values) {
      basket.push(values);
    },
    getItemCount: function () {
      return basket.length;
    },
    doSomething: doSomethingPrivate(),
    getTotal: function () {
      var q = this.getItemCount(),
        p = 0;
      while (q--) {
        p += basket[q].price;
      }
      return p;
    }
  }
}());


// basketModule is an object with properties which can also be methods
basketModule.addItem({
  item: 'bread',
  price: 0.5
});
basketModule.addItem({
  item: 'butter',
  price: 0.3
});
console.log(basketModule.getItemCount());
console.log(basketModule.getTotal());
// however, the following will not work:
console.log(basketModule.basket); // (undefined as not inside the returned object)
console.log(basket); //(only exists within the scope of the closure)

Initial URL

                                

Initial Description
The module pattern was originally defined as a way to provide both private and public encapsulation for classes in conventional software engineering.
In JavaScript, the module pattern is used to further emulate the concept of classes in such a way that we're able to include both public/private methods and variables inside a single object, thus shielding particular parts from the global scope. What this results in is a reduction in the likelihood of your function names conflicting with other functions defined in additional scripts on the page.

Initial Title
Javascript Module Pattern

Initial Tags
javascript

Initial Language
JavaScript