Tuesday, July 14, 2015

JavaScript Closures (Step 1 for App development)

JavaScript Closures

In this blog i like to write and discuss about the Closures in JavaScript, i am using JavaScript in SharePoint sites from 2007 version, In my first working assignment i was told to premeditate a Site template made using SPServices and Jquery to new SharePoint JavaScript client object model Site back in 2009, It was a Template which enables functionality of  Twitter on SharePoint. But that time i just created and written everything in functions which were added under Global namespace automatically.
And this is normally we do in creating our applications or making some modifications, but with the advancement in client side programming and trend of Single Page applications and many other factors  has introduced design patterns and writing javascript libraries.

To make such libraries one basic important concept is Closure.

A closure is concept made out of anonymous functions and a basic fact in javascript that an anonymous function can be returned from other functions, like it  can also be assigned to a variable

Local variables defined within the containing function are available through the returned anonymous function and this is called Closure.

Now lets see this in a series of examples:-


  1. Basic Closure example:-
    var Maddy = window.Maddy || {};
    
    Maddy.getStudentName = function Student(id) {
        var students = { '1': 'ankur', '2': 'nelson', '3': 'drew' };
        var getName = function () {
            alert(students[id]);
        };
        return getName;
    
    };
    
    Maddy.getStudentName(3)();
    


    here we have a namespace Maddy and under that we have a function getStudentName which incorporates an anonymous function accessing local variable students  and retrieving the value of name of student contained in students variable.

    We have just returned the function to the original function.
  2. The inner function is the closure in above example, it has three access chains, it can access its own variable and variables scoped to outer function and also can access Global function, but it can not access arguments directly of outer function, see this example:-

    Look at this example which does not use Closure:-

    Maddy.addArguments = function()
    {
        var sum =0;
        for(var i=0;i<arguments.length;i++)
        {
    
            sum += Number(arguments[i]);
        }
    
        return sum;
    }
    alert(Maddy.addArguments(1,2,3,4,5));
    
    

    It will work perfectly and will give you output of 15.

    Now if you use Closure and try to access arguments it wont work.

    Maddy.addArgumentsWithclosure = function () {
        var sum = 0;
    
        var doTheSum = function () {
            for (var i = 0; i < arguments.length; i++) {
    
                sum += Number(arguments[i]);
            }
    
            return sum;
        };
        return doTheSum;
    };
    
    alert(Maddy.addArguments(1,2,3,4,5)());
    

    it will return '0' in alert and wont work.

    So Closure can access local,outer and global variables but cant work with outer function arguments object.
  3. Closures have access to the outer function’s variable even after the outer function returns, also it stores references to the outer function’s variables;

    example demonstration:-

    Maddy.getValueID = function () {
        var valueId = 101;
    
    
        return {
    
            get_valueId: function () {
    
                return valueId;
            },
    
            set_valueId: function (newValue) {
                valueId = newValue;
            }
    
    
    
        };
    
    };
    
    var dummyVar = Maddy.getValueID();
    alert(dummyVar.get_valueId()); //output will be 101
    dummyVar.set_valueId(1000); 
    alert(dummyVar.get_valueId()); //output will be 1000
    
    
As shown above set_valueId closure still keeps reference to outer function variables even outer functions is allready executed.

No comments:

Post a Comment