Tuesday, June 10, 2014

How to create local modules in JavaScript

The module pattern can be used to make your function private and save it from global effects. JavaScript does not give any error even if you override the functions.

For example, if you have a global function like

function global() {
     console.log('I am global function.');
}

and now i create a new module function and override global function like this:

function newModule() {
     global = function() {
          console.log('I am new global.');
    }
}

If you run the above functions by calling:

global()
newModule()
global()

The output will be:

I am global function.
I am new global.

You can use module pattern to stop global overriding.

var module = {};

(function(exports) {
    exports.local = function() {
        console.log('I am local not global.');
    }
}(module));

Now you can call local function using:

module.local()

which will print:

I am local not global.

No comments: