Module layout in JavaScript


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

Simple illustration of structuring your JavaScript and minimising your use of global vars.


Copy this code and paste it in your HTML
  1. var myModule = function(){
  2. //Keep the vars outside the global namespace (global vars are evil!)
  3. var a = 122;
  4. var b = 22;
  5.  
  6. return {
  7. init: function(){
  8. console.info("The module has been initialised");
  9. },
  10. add: function(c){
  11. //c doesn't exhist so 0;
  12. c = c || 0;
  13.  
  14. var sumA = a + c;
  15. var sumB = b + c;
  16.  
  17. console.log(sumA);
  18. console.log(sumB);
  19. }
  20. }
  21. }();
  22.  
  23. myModule.init();//Initialise
  24. myModule.add(33);

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.