JavaScript: Closures

Simply put, a closure is a function in which another function, the inner function, is defined. The important part, when it comes to closures, is that the inner function remembers the environment in which it was created. What this really means is that when the inner function references the variables of the outer function, the inner function retains references to these variables even after the outer function terminates its execution and is no longer needed.

So why is this a useful feature of JavaScript, probably the most common use is as a ‘hack’ to create private state (variables) specific to a function and which can only be altered by the function that maintains a reference to that state. If you are familiar with C# or Java this can be compared to what is called encapsulation, where an object has state (variables) within it which only it can modify.

'use strict';

// Closures
//  9. Closures: Functions can be declared inside of other Functions
//     the Function has access to its own Parameters and Scope
//     but it also has access to the Parameters and Scope of the
//     Functions it is nested within
function encapsulator (param){
    var variable_in_scope = "I am in the Encapsulator.";

    function inner_function(inner_param){
        console.log("Inner Function param: " + inner_param);
        console.log("Outer Function param: " + param)
        console.log("Outer Function scope Variable: " + variable_in_scope);
    }

    try{
        console.log("Attempting to access Inner Function param from Outer Function: " + inner_param);
    }catch(error){
        console.log("ERROR: You cannot access the scope of an Inner Function: " + error.message);
    }

    inner_function("You are entering the Inner Function");
}

encapsulator("You are calling the Outer Function");

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s