Why global variables are bad?
- The primary reason why we need to avoid global scope is because all code share a single global namespace.
- JavaScript implied global namespace. i.e variables that are not explicitly not described in local scope are automatically added to global namespace
- Relying on this might result in collision between various scripts on the same page
- JavaScript does not have the concept of function overloading
Solution
Use YUI module pattern:
Implementation of this pattern includes wrapping all our code in a function that returns functions that needs to be accessed outside our module and assign the return value to a single global variable
var FOO = (function() { var my_var = 10; //shared variable available only inside your module function bar() { // this function not available outside your module alert(my_var); // this function can access my_var } return { a_func: function() { alert(my_var); // this function can access my_var }, b_func: function() { alert(my_var); // this function can also access my_var } }; })();
Easiest way
(function() { // Your code here // Expose to global window['varName'] = varName; })()
No comments:
Post a Comment