Posted By

johnloy on 02/17/09


Tagged

javascript textmate design-pattern


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

inkdeep
kcmr
indamix


variations of the Javascript module pattern


 / Published in: Other
 

  1. var myModule = function () {
  2.  
  3. var publicObj = {}; // returnable object...
  4.  
  5. var privateProperty = "I can be accessed only from within this module";
  6. var privateMethod = function () {
  7. // has access to public properties as publicObj.publicVar and private methods
  8. }
  9.  
  10. var publicObj.publicProperty = "Publicly accessible as myModule.publicVar.";
  11. var publicObj.publicMethod = function () {
  12. // Publicly accessible as myModule.publicMethod
  13. }
  14.  
  15. return publicObj;
  16.  
  17. }();
  18.  
  19.  
  20. var myModule = function(){
  21.  
  22. var privateMethod = function(){
  23. publicMethod();
  24. }
  25.  
  26. var publicMethod = function(){
  27. return this;
  28. }
  29.  
  30. // Copy over methods you want to be public
  31. return {
  32. publicMethod : publicMethod
  33. }
  34.  
  35. }();
  36.  
  37.  
  38. var myModule = function(){
  39.  
  40. // Persists in privateMethods due to closure
  41. var that = {};
  42.  
  43. function privateMethod(){
  44. that.publicMethod();
  45. }
  46.  
  47. return {
  48. publicProperty: true,
  49. publicMethod: function(){},
  50. // Make this visible in private scope
  51. init: function(){
  52. that = this;
  53. }
  54. };
  55.  
  56. }().init();

Report this snippet  

You need to login to post a comment.