The following is my learning to remember, if there is wrong, please point out.
1. Scope of variables
Variables in JavaScript fall into two categories, depending on their scope: global variables and local variables.
Global variables can be read directly from inside a function:
var a = 1;
function fn1() {
console.log(a);
}
fn1(); / / 1
Copy the code
However, local variables inside a function cannot be read from outside the function:
function fn2() {
var b = 2;
}
console.log(b); // ReferenceError: b is not defined
Copy the code
Var, const, or let; window.b = 2; window.b = 2;
function fn2() { b = 2; } fn2();} fn2(); console.log(b); / / 2Copy the code
2. Introduce closures
So how do you access variables inside a function from outside the function?
Just define another function inside the function and return it as a function:
function fn1() {
var a = 1;
return function fn2() {
console.log(a);
};
}
// Because fn1 has a return value, it is received with result
var result = fn1();
result(); / / 1
Copy the code
Thus, outside of function fn1, the function result is executed, and the variable A inside function fn1 is accessed.
This makes for a simple closure. In the example above, fn2 is actually a closure function.
A closure is simply a function that can access variables inside other functions.
3. What closures do
As you can see from the above example, the first effect of closures is that they can access variables inside a function from outside of it.
Another function of closures is to keep variable objects in memory in the context of a function that has finished running. Watch the following demo:
function fn1() {
var a = 1;
return function fn2() {
console.log(a++);
};
}
var result = fn1();
result(); / / 1
result(); / / 2
result(); / / 3
Copy the code
A is a local variable in the function fn1, and the value of a changes in the function fn2, which is +1 every time fn2 is executed.
After executing result() three times, the preceding code outputs the value of a, with a continuously +1. This indicates that the variable a in function fn1 is always in memory and is not cleared after function fn1 is called.
Because the function fn2 is assigned to a global variable, fn2 is always in memory, and fn2’s existence depends on fn1, so fn1 is always in memory and is not garbage collected after being called.
4. Side effects of closures
❗ Memory consumption
Closures cause variables in a function to be stored in memory, which consumes a lot of memory. Closures should not be abused, or it will cause serious performance problems, which may lead to memory leaks in IE.
Solution: Before exiting the function, clear all unused local variables.
❗ Error the value inside the function
Do not change the value of the internal variable of the parent function.
Learning Javascript Closures