When to use clousures?

0

I have the following code:

function creaSumador(x) {
  return function(y) {
    return x + y;
  };
}

var suma5 = creaSumador(5);
var suma10 = creaSumador(10);

console.log(suma5(2));  // muestra 7
console.log(suma10(2)); // muestra 12 

I can do it myself

function suma(x,y) {
 
    return x + y;
  
}



console.log(suma(5,2));  // muestra 7
console.log(suma(10,2)); // muestra 12 

I do not see much importance to the functions clousures , since it can also be done without clousures , can you explain me when to use clousure , when in fact it is necessary?

    
asked by hubman 23.12.2016 в 21:29
source

1 answer

3

I find it useful when creating 'public' or 'private' properties:

var functions = (function () {
    var private = 'this is private'; 

    return {
        publicAccess: function () {
            return private;
        }
    }
})(); 

Then in this way the variable functions would only have access from outside to publicAccess. You can not change the private directly by accessing it.

    
answered by 23.12.2016 в 21:39