Wednesday, April 12, 2017

Avoiding global scope in java script


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
        }
    };

})();
To use functions in your module elsewhere, we use FOO.a_func(). To avoid global namespace conflict we need to only change the name of FOO.

Easiest way


(function() {
    // Your code here

    // Expose to global
    window['varName'] = varName;
})()

No comments:

Post a Comment