Anonymous functions and closures
An anonymous function is a function that does not have a name, and a closure is a function that accesses variables in a function scope.A anonymous functions
//Common functions
Functionbox () {//The function name isBox
Return ' Lee ';
}
//anonymous functions
function () {//anonymous function, will error
Return ' Lee ';
}
//Self-executing with an expression
(function box () {//Encapsulated as an expression
Alert (' Lee ');
})();//()Represents an execution function, and the parameter is passed
//Assigning anonymous functions to variables
var box = function () {//Assigning an anonymous function to a variable
Return ' Lee ';
};
Alert (Box ());//Similar to call methods and function calls
//Anonymous functions in a function
Functionbox () {
Returnfunction () {//Anonymous functions in the function, resulting in closures
Return ' Lee ';
}
}
Alert (Box () ());//Calling anonymous functions
Two Closed Package
Closures are functions that have access to variables in another function scope, and the common way to create closures is to
Create another function inside one function to access the local variables of the function through another function.
//You can return a local variable by closing a packet
Functionbox () {
Varuser= ' Lee ';
Returnfunction () {//Returned by an anonymous functionBox ()Local variables
Returnuser;
};
}
Alert (Box () ());//PassBox () ()To call the anonymous function return value directly
Varb=box ();
Alert (b ());//Another call to the anonymous function returns a value
The use of closures has an advantage, but also its disadvantage: it is possible to place local variables in memory, you can avoid the
Use global variables.(Global variable pollution leads to application unpredictability, and each module can invoke a disaster,
Therefore, it is recommended to use a private, encapsulated local variable)。
//To accumulate by global variables
varage=100;//Global variables
Functionbox () {
age++;//The module level can call global variables and accumulate
}
Box ();//Execute function, accumulate
alert (age);//Output Global Variables
//Accumulation cannot be achieved by local variables
Functionbox () {
varage=100;
age++;//Accumulation
Returnage;
}
Alert (Box ());101
Alert (Box ());101, could not be implemented because it was initialized again
//The accumulation of local variables can be realized by closures
Functionbox () {
varage=100;
Returnfunction () {
age++;
Returnage;
}
}
var b = box (); // get function
Alert (b ()); // Call anonymous function
aler
Anonymous functions and closures