Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Javascript Closures

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 168
    Comment on it

    Closures are functions that are used to free variables which means variables are used locally, but defined in an enclosing scope. With the help of closures, JavaScript programmers are able to write better code.

    A closure is an inner function that has access to the external (enclosing) function's variables—scope chain.
     The conclusion has three extension chains: 
    1. It has access to its own scope (variables characterized between its curly brackets),
    2. It has access to the external function's variables, and 
    3. It has access to the global variables.

    Closure can be created by adding a function inside another function. Here is the basic example of closure in javascript :-

    function showName (firstName, lastName) {
    var nameIntro = "Your name is ";
        // this inner function has access to the outer function's variables, including the parameter
    function makeFullName () {        
    return nameIntro + firstName + " " + lastName;    
    }
    
    return makeFullName ();
    }
    
    showName ("john", "smith"); // Your name is john smith

    Closures are also frequently used in jQuery. Here is the basic Jquery code :-

    $(function() {
    
    var selections = []; 
    $(".niners").click(function() { // this closure has access to the selections variable
    selections.push (this.prop("name")); // update the selections variable in the outer function's scope
    });
    
    });

    Some important points to remember :-

    1. Closures have rights to access to the outer function's variable even after the outer function returns. At the point when JavaScript function execute, they utilize the same chain when created. This implies if the outer function has given back, the inner function still has access to the outer function's variables. In this way, you can call the inner function later in your program. This illustration illustrates:

    function celebrityName (firstName) {
        var nameIntro = "This celebrity is ";
        // this inner function has access to the outer function's variables, including the parameter
       function lastName (theLastName) {
            return nameIntro + firstName + " " + theLastName;
        }
        return lastName;
    }
    
    var mjName = celebrityName ("John"); // At this juncture, the celebrityName outer function has returned.
    
    // The closure (lastName) is called here after the outer function has returned above
    // Yet, the closure still has access to the outer function's variables and parameter
    jsName ("Smith"); // This celebrity is John Smith

    2. As closures can access  the updated values of the outer function’s variables, they can also lead to bugs when the outer function’s variable changes with a for loop. 

    // This example is explained in detail below (just after this code box).
    function celebrityIDCreator (theCelebrities) {
        var i;
        var uniqueID = 100;
        for (i = 0; i < theCelebrities.length; i++) {
          theCelebrities[i]["id"] = function ()  {
            return uniqueID + i;
          }
        }
        
        return theCelebrities;
    }
    
    var actionCelebs = [{name:"jacky", id:0}, {name:"Abrahm", id:0}, {name:"John", id:0}];
    
    var createIdForActionCelebs = celebrityIDCreator (actionCelebs);
    
    var stalloneID = createIdForActionCelebs [0];console.log(stalloneID.id()); // 103

    In the former case, when the anonymous functions are called, the estimation of i is 3 (the length of an array and after that it increases). The number 3 was added to the uniqueID to make 103 for ALL the celebritiesID. So every position in the returned array get id = 103, rather than the proposed 100, 101, 102. 

    The reason this happened was on the grounds that, as we have examined in the past case, the conclusion (the anonymous functions in this case) has entry to the external capacity's variables by reference, not by quality. So pretty much as the past case demonstrated that we can get to the upgraded variable with the conclusion, this illustration comparably got to the i variable when it was changed, subsequent to the external capacity runs the whole for circle and returns the last estimation of i, which is 103. 

    To alter this symptom (bug) in terminations, you can utilize an Immediately Invoked Function Expression (IIFE, for example, such as the following:

    function celebrityIDCreator (theCelebrities) {
        var i;
        var uniqueID = 100;
        for (i = 0; i < theCelebrities.length; i++) {
            theCelebrities[i]["id"] = function (j)  { // the j parametric variable is the i passed in on invocation of this IIFE
                return function () {
                    return uniqueID + j; // each iteration of the for loop passes the current value of i into this IIFE and it saves the correct value to the array
                } () // BY adding () at the end of this function, we are executing it immediately and returning just the value of uniqueID + j, instead of returning a function.
            } (i); // immediately invoke the function passing the i variable as a parameter
        }
    
        return theCelebrities;
    }
    
    var actionCelebs = [{name:"jacky", id:0}, {name:"Abrahm", id:0}, {name:"John", id:0}];
    
    var createIdForActionCelebs = celebrityIDCreator (actionCelebs);
    
    var stalloneID = createIdForActionCelebs [0];
    console.log(stalloneID.id); // 100
    
    var cruiseID = createIdForActionCelebs [1];console.log(cruiseID.id); // 101

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: