Conditions that generate closures
The inner function can access the scope of the outer function.
function init() {
var name = "Mozilla"; // Name is a local variable created by init
function displayName() { // displayName() is an inner function, a closure
alert(name); // Use a variable declared in the parent function
}
displayName();
}
init();// Console run result: Mozilla
//
Copy the code
The role of closures
- Causes variables inside a function to remain in memory after the function completes execution (extends the life of local variables)
- A variable or function that enables an external function to operate on an internal function
` `
function foo(){
var a=3;
function b(){
a++;
console.log(a)
}
function c(){
a--;
console.log(a)
}
return c;
}
foo()();// console Execution result: 2
Copy the code
The life cycle of closures
Generation of closures: Generation of internal nested function definitions after completion of execution.
Closure death: When internally nested functions become junk objects
Application of closures
- A JS file with a specific function
- Encapsulate all data and functionality inside functions that are private
- Only one object or function containing n methods is exposed
- The consumer of the module only needs to invoke the exposed object invocation method to implement the corresponding function
Method 1
// The following is the internal code of js file: mymodule.js
function muModule(){
/ / private
var msg='My atguigu'
funtion doSomething(){
console.log('doSomething()'+msg.toUpperCase())
//
}
funtion.doOtherthing(){
console.log('doOtherthing() '+ msg.tolowerCase ())} return{doSomething: doSomething, doOtherthing: DoOtherthing}// expose only one object or function containing n methods}