Here is another quick tip on creating modular JavaScript, namely function wrappers, or more technically called Immediately-Invoked Function Expression (IIFE). A self-invoking anonymous function runs automatically/immediately when you are create it, but don’t confuse it with document.ready or window.onload.
The basic of IIFE is to use a wrapper so that it does not pollute the global namespace, all variables used inside the function will not be visible to the outside scope. You may have seen this kind of code, something along the line of:
1 2 3 |
(function() { //code code code })(); |
For example the variable defined below bar will not be able to access it outside the scope.
IIFE provides a protection/encapsulation to your code.
1 2 3 4 5 |
(function() { var bar = "hello"; })(); bar = "world"; // <-- Error, we dont know what bar is so its undefined |
If you wish to pass in data to your anonymous function, for example in our code below we are passing in the global window object to our function.
1 2 3 4 |
(function(w) { var height = w.height; })(window); |
The last benefit of using the IIFE, is that it provides a way to create more modular Javascript.
The code below shows a module called counterModule and how we use it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
var counterModule = (function() { var count = 0; return { increment: function() { count++; }, decrement: function() { count--; }, print: function() { alert(count); }, reset: function() { count = 0; } }; })(); counterModule.increment(); //count = 1 counterModule.increment(); //count = 2 counterModule.print(); //alert box 2 counterModule.reset(); //back to 0 counterModule.print(); //alert box 2 |
And if you have written any JQuery plugin you may have already seen the module pattern used for plugins. In the code below we are injection Jquery into our anonymous function.
1 2 3 4 5 6 7 |
(function($) { $.fn.helloWorld = function() { return this.each( function() { $(this).text("Hello, World!"); }); } }(jQuery)); |
This is the very basic of a module pattern, and if you wish to read more about the module pattern I suggest you Addy Osmani book on Javascript Design Patterns
increment: function() { count++; },
decrement: function() { count–; },
print: function() { alert(count); },
reset: function() { count = 0; }
};
})();
counterModule.increment(); //count = 1
counterModule.increment(); //count = 2
counterModule.print(); //alert box 2
counterModule.rest(); //bac ******************typo reset not rest
Thanks 🙂