Advertisement
Guest User

Untitled

a guest
Jun 28th, 2017
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.73 KB | None | 0 0
  1. // Define a closure to wrap all your code
  2. (function() {
  3.  
  4. // Private var. This var is not accesible outside closure.
  5. var privateVar1 = "test value";
  6.  
  7.  
  8. // Private function. This function is only accesible inside this closure.
  9. function privateFunction1() {
  10. var localVar = privateVar1 + "aaa";
  11. }
  12.  
  13.  
  14. /** We use window global object to export this function
  15. * to global context and do it public.
  16. * One problem with this, is that outside we can override
  17. * ref to this function doing:
  18. * window.publicFunction2 = otherFunctionOrWhatever;
  19. **/
  20. window.publicFunction2 = function(arg1, arg2) {
  21. // We can use here, private vars and functions
  22. var localVar2 = privateFunction1() + privateVar1;
  23. //...
  24. }
  25.  
  26.  
  27. /** We use window global object to export this variable
  28. * to global context and do it public.
  29. * This variable is read-writeable
  30. **/
  31. window.publicVar2 = "test value 2";
  32.  
  33.  
  34. /** Example of exporting a module-like.
  35. * A module is a set of functions and classes that
  36. * are related and it access following way:
  37. * moduleName.function(...)
  38. **/
  39. window.moduleName = {
  40. /**
  41. * Example of function in module.
  42. **/
  43. function1: function(arg1, arg2, arg3) {
  44. //...
  45. // 'this' is whole module
  46. this.function1(3, 4, 5);
  47. },
  48.  
  49. /**
  50. * Example of a class definition inside a module
  51. **/
  52. clase1: function Clase1(arg1) {
  53. // create instance outside:
  54. // var objClase1 = new moduleName.clase1(3);
  55.  
  56. // @see OOP.js to see how to define a class
  57. }
  58. }
  59.  
  60. })();
  61.  
  62.  
  63. // Public function. This function is accesible wherever
  64. function publicFunction3() {
  65. // We can use public functions and vars for example
  66. // from closure
  67. var localVar3 = publicFunction2(2, 3) + publicVar2
  68. + publicVar3;
  69.  
  70. //...
  71. }
  72.  
  73.  
  74. var publicVar3 = "test value 3";
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement