Js closure instance summary

  • 2020-03-30 04:17:00
  • OfStack

Js closure
What to know before a closure
1. Function scope
(1).Js language is special in that the function can directly read global variables


<script type="text/javascript">
var n=100;
function parent(){
  alert(n);
}
parent();//100
</script>

If you're in PHP


<?php
$n=100;
function parent(){
  echo $n;
}
parent();//N not defined
?>

(2). Local variables in the function cannot be read outside the function


<script type="text/javascript">
function parent(){
  var m=50;
}
parent();
alert(m);//Error m not defined
</script>

Note that you must add var when declaring variables inside a function, otherwise you declare a global variable


function parent(){
m=50;
}
parent();
alert(m);//50

// of course this is especially true in PHP,


<?php
function parent(){
  global $m;//Globally, definition and assignment are separated
  $m=50;
}
parent();
echo $m;//50
?>
//Without global, an undefined error
is also reported

Sometimes, need to be local variables within the function, requires flexible method using js, the characteristics of variable scope, function, as defined within the function for a subroutine, father function is its global, son function can access the father of the variable in a function (for the js code and local variables)


<script type="text/javascript">
function parent(){
   var m=50;
   function son(){
        alert(m);
   }
   return son;
}
var s=parent();//Save the result in the global
s();//50
</script>

All local variables within the Parent is visible for its function, but its local variables within the function of his father's function is not visible, this is js the scope chain structure, child objects will be cascaded upward to find all the Parent object variables, subsidiary to the Parent of all variables object is visible, not stand on the contrary! The son function above is the closure
Some of you might


function parent(){
   var m=50;
   function son(){
        alert(m);
   }
}
parent();
son()//The return function son is not defined

Notice that in javascript, all the functions that are declared in a function are local, and are released when the function is run
Note the difference with PHP


<?php
function parent(){
  function son(){
      $m=50;
      echo $m;
  }
}
parent();
son();//Output 50 with no errors
?>

closure

Functions define functions internally and bridge functions internally and externally
Closures have two functions:
One is the variables inside the read function,
The second is to keep the values of these variables in memory and realize data sharing
Here are a few examples of closures


<script type="text/javascript">
var cnt=(function(){
    var i=0;
    return function(){
        alert(i);
        i++;
    }
})();
cnt();//0
cnt();//1
cnt();//2
cnt();//3 </script>

The result of the execution of the anonymous function (that is, the declaration of the inside function assigned to the global variable cut) is stored in memory
When the cut() is executed, it is evaluated directly from memory. I can only be called by the CNT () function
You can also pass arguments into a closure


var cnt=(function(num){
return function(){
    alert(num);
    num++;
  }
})(5);
cnt();//5
cnt();//6
cnt();//7
//Of course, you can also call the time reference
var cnt=(function(){
    var i=0;
return function(num){
    num+=i;
    alert(num);
    i++;
  }
})();
cnt(1);//1
cnt(2);//3
cnt(3);//5

For a better understanding of closures, let's look at the following code
Let's say I want to return an array of 5 functions, the first function pops up 0, the second one pops up 1...  
If you write the code like this


function box(){
  var arr=[];
  for(i=0;i<5;i++){
      arr=function(){return i;}
    }
return arr;  
}
var a=box();
alert(a);//An array of five function bodies
alert(a[0]());
alert(a[1]());

The body of the function that pops up
The function () {return I; }       }
This last I is 4, and then plus plus becomes 5
For loop stop
It is found that all pop up 5, which obviously does not meet our requirements

Solution 1
I execute the functions in real time


function box(){
  var arr=[];
  for(i=0;i<5;i++){
      arr=(function(num){return i;})(i);
    }
return arr;  
}
var a=box();
for(var i=0;i<a.length;i++){
  alert(a);
}

But we found that the elements in the returned array were the result of the function's execution, but we wanted the function to have to upgrade our code

Solution 2
Closure implementation


function box(){
var arr=[];
        for(var i=0;i<5;i++){                  arr=(function(num){
                     return function(){return num;}
                 })(i);          }
return arr;        
} var arr=box(); for(var i=0;i<5;i++){     alert(arr());//0,1,2,3,4
}

The key code


arr=(function(num){
         return function(){return num;}
})(i);
i=0 when
arr[0]=(function(num){return function(){return num;}})(0); 1 when
arr[1]=(function(num){return function(){return num;}})(1); 

  Those are the benefits of closures! Very simple and practical.


Related articles: