Javascript Module Pattern


/ Published in: JavaScript
Save to your folder(s)

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.


Copy this code and paste it in your HTML
  1. var basketModule = (function () {
  2. var basket = []; //private
  3. function doSomethingPrivate() {
  4. //...
  5. }
  6. function doSomethingElsePrivate() {
  7. //...
  8. }
  9. return { //exposed to public
  10. addItem: function (values) {
  11. basket.push(values);
  12. },
  13. getItemCount: function () {
  14. return basket.length;
  15. },
  16. doSomething: doSomethingPrivate(),
  17. getTotal: function () {
  18. var q = this.getItemCount(),
  19. p = 0;
  20. while (q--) {
  21. p += basket[q].price;
  22. }
  23. return p;
  24. }
  25. }
  26. }());
  27.  
  28.  
  29. // basketModule is an object with properties which can also be methods
  30. basketModule.addItem({
  31. item: 'bread',
  32. price: 0.5
  33. });
  34. basketModule.addItem({
  35. item: 'butter',
  36. price: 0.3
  37. });
  38. console.log(basketModule.getItemCount());
  39. console.log(basketModule.getTotal());
  40. // however, the following will not work:
  41. console.log(basketModule.basket); // (undefined as not inside the returned object)
  42. console.log(basket); //(only exists within the scope of the closure)

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.