Understanding JavaScript: Closures

in #programming7 years ago (edited)

To summarize a lot, we could say that closures in JavaScript are composed of a function (let's call it external) that contains another function (let's call it internal). The internal function has access to the variables of the external function, creating a context that is persistent through different calls. If the definition seems convoluted, take a look at the article I used earlier, since with examples is understood much better.

And once we know what closures are, let's see how we can use them.

Public and private variables

In JavaScript, we do not have any reserved words that allow you to declare variables or functions as private. Let's say there is no private that restricts the visibility of a method or property outside the object.

var Person=function(){
    // Esta variable es privada
    var savedName=“anónimo”;return{
        getName: function(){
            returnsavedName;
        },
        setName: function(name){
            savedName=name;
        }
    }
}();

In the example we are creating a new anonymous function with a variable that will be private, and a return that returns the two internal JavaScript functions. The variable is private, because we do not have access from outside the function, but the functions returned by the return do have it, since they are in the same context as the outer function. In short, the variables are inside the closure and the internal functions have access to them. To finish clarifying the concept, an example of the execution.

//Hello undefined, because we do not have access to the variable

document.write(“Hola”+Person.savedName);

//Hola anónimo, because the variable still has the value

document.write(“Hola”+Person.getName());

//We change the new value of the private variable

Person.setName(“Cylon”);

//It prints Hola Cylon

document.write(“Hola”+Person.getName());

This functionality of the closures is very useful, and using this pattern, we can create more robust JavaScript code, controlling which properties or methods can be called, and which ones are not.

Functions that call themselves
This is a curious application of closures. Let's look at an example:

(function(name){
    document.write(“Hola”+name);
})(“Cylon”);

In this case, the anonymous function that is inside the parentheses, and that receives a parameter, returns an object. This object is a function with its context, which in this case is the name variable. Just after, with another parenthesis, we call the function by passing the value to the name parameter. It is actually a faster way of doing the same thing we did in the previous article, explaining closures:

var example=function(name){
    returnfunction(){
        document.write(“Hola”+name);
    }
};
varhelloCylon=example(“Cylon”);
helloCylon();

Así que con las funciones que se llaman a si mismas, tenemos un mecanismo interesante para ejecutar código bien encapsulado.

Funciones generadoras

Como veíamos en el artículo anterior, con el ejemplo de la hucha, podemos utilizar los closures para generar objetos totalmente independientes a partir del mismo código. Veamoslo con un ejemplo distinto:

function warnMessage(message) {
    return function () {
        alert(“Warning: ” + message);
    }
};

$(document).ready(function () {

    var message1 = warnMessage(“El nombre es obligatorio”);
    var message2 = warnMessage(“La edad es obligatoria”);

    $(“#name”).click(message1);
    $(“#age”).click(message2);

});

We have created a function called warnMessage, which is responsible for creating a function that will launch an alert with a certain message. Then we create two different objects, with the generating function and associate them directly to the click event of JQuery. When you click on these items, which may be buttons, the specified message will be displayed. Very useful.

Sort:  

Hi Javascript Steemians

Please have a look at JSEcoin it is a new coin that is mined through a web browser so anybody can mine! Its very new so will be easier now to earn coins and there is a free initial bonus

Here is a referred link:

https://jsecoin.com/platform/?register=1&utm_source=referral&utm_campaign=aff270&utm_content=

Many thanks

BlueRiverCard

This post recieved an upvote from minnowpond. If you would like to recieve upvotes from minnowpond on all your posts, simply FOLLOW @minnowpond

This post recieved an upvote from minnowpond. If you would like to recieve upvotes from minnowpond on all your posts, simply FOLLOW @minnowpond

Resteem your post to 1300+ followers for only 0.5 SBD or Steem)

Just send 0.5 SBD or steem to @steemvote (URL as memo)

New Followers get 0.001 SBD$ and an upvote for free!!

Just follow @steemvote and...

  • we follow back
  • send you 0.001 SBD to your wallet