Javascript revealing module pattern template


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

"Javascript module pattern emulates 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/namespacing particular parts from the global scope."
When inheritance is not needed and a only few instances is needed (Keep in mind that each instance places a new copy of each function in memory!)


Copy this code and paste it in your HTML
  1. /*
  2.  The idea here is that you have private methods
  3.  which you want to expose as public methods.
  4. */
  5.  
  6. var SomeModule = (function(param){
  7. // Private stuff
  8. // 'this' keyword refers to the current instance. Must use 'new' when creating instances of the module, else 'this' will refer to global scope.
  9. this.initval = param;
  10. this.name = 'John Smith';
  11. this.age = 40;
  12.  
  13. function setPerson(param) {
  14. this.name = param;
  15. }
  16.  
  17. function getPerson() {
  18. return this.name; // create closure (inner function) to bind the var (= keep it around)
  19. }
  20. // Public stuff / reveal and bind
  21. return {
  22. set: this.setPerson,
  23. get: this.getPerson,
  24. age: this.age
  25. };
  26. });
  27.  
  28. // creating instances
  29. var newModule = new SomeModule(newparam);
  30. newModule.set("Some Name");
  31. var name = newModule.age;
  32. var name = newModule.get;

URL: http://www.addyosmani.com/resources/essentialjsdesignpatterns/book/#designpatternsjavascript

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.