The closure I understand

Closure concept: a function that has access to variables in another function scope.

function add(){
     var result;
    result = function(x,y){
          return y+x     
    }   
    return result             
}

var sum = new add();
console.log(sum(10,20))/*30*/

The main reason for function execution is ()

function createFunctions(){
    var result = new Array();
    for (var i=0; i < 10; i++){
         result[i] = function(){
                  return i;
        };
               
    }
    return result;
}
var funcs = createFunctions();

for (var i=0; i < funcs.length; i++){
     console.log(funcs[i]());
}
/*Print out 10 10*/

The reason is that the returned functions all refer to the variable i, but it is not immediately executed until the function returns I = 10

function createFunctions(){
     var result = new Array();
    for (var i=0; i < 10; i++){
        result[i]=(function(num,count){
            return function (){
                return num+count
             }
         })(i,3)
    }
    return result;
}
var funcs = createFunctions();

for (var i=0; i < funcs.length; i++){
     console.log(funcs[i]());
}
/*Print correctly 1-10*/

Internally, there is an immediate execution function, that is, execution environment.

 

Leave a Reply

Your email address will not be published. Required fields are marked *