JavaScript Closures

A JavaScript Closure is formed by returning a function object that was created within an execution context of a function call from that function call and assigning a reference to that inner function to a property of another object. Or by directly assigning a reference to such a function object to, for example, a global variable, a property of a globally accessible object or an object passed by reference as an argument to the outer function call.

In the example below you will notice that the globalVar has access to the exampleConcatReturn. However, it does not have access to the finishStringArg as that is seen as basically a private variable that cannot be accessed outside that function.

function exampleClosure(stringArg1, stringArg2) {
    var finishStringArg = "!";
    function exampleConcatReturn(innerArg) {
        return (stringArg1 + stringArg2 + innerArg + finishStringArg);
    }

    return exampleConcatReturn;
}

var globalVar = exampleClosure("Adam ", "Drummond "); /*stringArg1 = "Adam" and stringArg2 = Drummond*/

//Call to the function
alert(globalVar("Was Here")); /* innerArg = "Is Coding" */

/* would return Adam Drummond Was Here!*/

Another example is as follows.  This was based from Mozilla’s developers area.  I think it really does a great job in showing how the privateCounter is only used from within.  Also, you will take notice that you can create numerous functions off of the main makeCounter function and they will stay separate of each other.

var makeCounter = function () {
    var privateCounter = 0;
    function changeBy(val) {
        privateCounter += val;
    }
    return {
        increment: function () {
            changeBy(1);
        },
        decrement: function () {
            changeBy(-1);
        },
        value: function () {
            return privateCounter;
        }
    };
};

var Counter1 = makeCounter();
var Counter2 = makeCounter();

alert(Counter1.value()); /* Alerts 0 */

Counter1.increment();
Counter1.increment();

alert(Counter1.value()); /* Alerts 2 */

Counter1.decrement();

alert(Counter1.value()); /* Alerts 1 */

alert(Counter2.value()); /* Alerts 0: Notice that it doesn’t get affected by Counter1 */

As seen in this example, you have Counter1 and Counter2.  Take a look at the incrementing and decrementing of Counter1 and at the end, Counter2 is still in the same state as when it was created.


Leave a Reply

Your email address will not be published. Required fields are marked *

StackOverflow Profile