anonymous functions
1 //assigning anonymous functions to variables2 varbox=function()3 {4 return' Lee ';5 }6 7 //anonymous functions self-executing to execute anonymous functions8(function()9 {TenAlert (' Lee '); One })(); A //assigning the return value of an anonymous function to a variable - varbox = (function() - { the return' Lee '; - })(); - - alert (box); + //arguments for self-executing anonymous functions - +(function(age) A { at alert (age); -}) (100);
Closures are functions that can access variables in a function scope
1 //an anonymous function is placed inside the function2 functionbox ()3 {4 return function()5 {6 return' Lee ';7 }8 }9 Ten //Alert (Box () ()); One A varb=box (); -Alert (b ());
A closure is a function that accesses a variable in the scope of another function, and the common way to create closures is to create another function inside one function and access the local variables of the function through another function.
1 //returning local variables via closures2 functionbox ()3 {4 varAge = 100;5 return function()6 {7 returnAge ;8 }9 }Ten OneAlert (Box () ());
Closures can place local variables in memory, avoiding the use of global variables. (Global variables pollute to the point when application unpredictability, each module can be called will inevitably lead to disaster, so it is recommended to use private, encapsulated local variables)
1 //using anonymous functions to implement local variables that reside in memory to accumulate2 functionbox ()3 {4 varAge = 100;5 return function()6 {7age++;8 returnAge ;9 }Ten } One A //alert (b () ()); This accumulation cannot be used because the Var age =100 is initialized every time; - - varb=box (); the alert (b ()); - alert (b ()); - alert (b ()); - alert (b ()); + alert (b ()); - +b=NULL;//★★this is very important. dereference Garbage collection
javascript-anonymous function, closure basic finishing (1).