Wednesday, July 2, 2014

03 - IIFE and Modules


Current there are neither classes nor namespaces in JavaScript. However, we could  modularize JavaScript code with the Immediately Invoked Function Expression (IIFE).

Firstly, let's define a variable and two functions as the following, without modularization:

var count = 0;

function print()
    console.log(count);
}

function increase()
{
    count++;
}

In the code above, the function names print and increase are available globally, and it is highly possible for them to conflict with other variable or function names. Therefore, it is necessary to protect them inside a module.

The first modularization solution is to utilize objects. The variable and functions become members of an object, as listed below:

var module = new Object({
    count: 0,

    print: function() {
        console.log(this.count);
    },

    increase: function() {
        this.count++;
    }
});

The problem with this solution is that the member variable count is accessible outside the object, which usually is not our purpose because we would like to hide data but just expose interfaces. The following code shows how to modify the member variable count:

module.count = 5;
module.increase();
module.print(); // 6

The member variable count is initialized as 0 firstly. It is increased to 6 then, so the output is 6.

A better solution to modularize is to utilize IIFE. The code above can be refined into the following section of code:

var module = function() {
    var count = 0;

    var print = function() {
        console.log(count);
    };

    var increase = function() {
        count++;
    };

    return {
        print: print,
        increase: increase
    };
}();

In the code above, count is a local variable inside the anonymous function, and it is inaccessible outside the function. Therefore, only the interfaces are exposed but the details are hidden.

We could demonstrate that the variable count is inaccessible with the following piece of code:

module.count = 5; 
module.increase();
module.print(); // 1

Even though we try to set module.count as 5, it actually inserts a property count with value 5 into the object returned by the anonymous function, but the variable count inside the function keeps unchanged. After the variable count increases, it becomes 1, so the output is 1, instead of 6.

No comments :

Post a Comment