Closure function
1. Let the variable reside in memory
2. Private variables inside the function can be read outside the function
1 <!DOCTYPE HTML>2 <HTMLLang= "en">3 <Head>4 <MetaCharSet= "UTF-8">5 <title>anonymous function +closure</title>6 <Scripttype= "Text/javascript">7 8 window.onload= function(){9 varElems=document.getElementsByTagName ('a');Ten for (varI= 0; I<elems.length; I++) { One (function(lockindex) { A Elems[lockindex].addeventlistener ('Click', function(event) { - //body ... - Console.info (lockindex);// the }, false); - }) (i); - }; - } + </Script> - </Head> + <Body> A <ahref= "#none">Save status with closures</a><BR/> at <ahref= "#none">As with normal function execution of the time parameters, self-executing functions of the expression can also be such a parameter, because the closure can directly refer to the parameters passed in, using these locked parameters, self-executing function expression can effectively save the state.</a><BR/> - <ahref= "#none">This code is wrong, because the variable i has never been back locked live</a><BR/> - <ahref= "#none">This is available because he is inside the self-executing function expression closure</a> - </Body> - </HTML>
Simulating private variables
1 function Counter (start) {2 var count = start;3 return {4 increment:function () {5 ++count;6 },7 getcount:function () {8 return count;9 }Ten } One } A - var obj = Counter (ten); - the obj.increment ();//count self-added - - var count = Obj.getcount ();//11 - + obj.increment ();//count self-added - +var count2 = Obj.getcount (); 12
Here, the Counter
function returns two closures, functions, increment
and Functions get
. Both of these functions maintain references to external scopes Counter
, so you can always access the variables defined within this scope count
.
1 for (var i = 0, len = 3; i < Len; i++) {2 (function (lockindex) { 3 var count = Lockindex; When the anonymous function init initializes--the copy of the loop variable i is assigned to the variable count 4 setTimeout (function () {5 console.log (' count ' +count); 6 }, 7 }) (i) 8 } 9 for (var i = 0, len = 3; i < Len; i++) { setTimeout (function (lo Ckindex) {$ var count = Lockindex; COPY14 console.log (' Count ' +count) of the cyclic variable i;
Learn JavaScript closures (Closure)