Talk about closures, talk about [JS] carefully

When is the closure?

        Closures are functions that can read variables inside other functions . In essence, a closure is a bridge that connects the inside of a function with the outside. In layman's terms , functions are nested functions , and the inner functions are closures . Feature: When the closure can be called, the function in the outer function will not be destroyed .

form

1. The return value is a function

2. The parameter is a function

 3. Immediately execute the function package function

 

significance

Extend the lifetime of variables, create private environments.

Scenes

1. It can be used to encapsulate code. For example, if you have written a bunch of programs with variables and functions, you can’t release them all at once. You can use closures to encapsulate them in a module. 【such as class】

//闭包之前
let a = 10;
let b = 20;
function add() {
    return a+b;
}
function sub() {
    return a-b
}
add();
sub();

//闭包之后
let module = (function() {
                    let a = 10;
                    let b = 20;
                    function add() {
                            return a+b;
                            }
                    function sub() {
                            return a -b;
                            }
              })()
module.add();
module.sub();

principle

Scope chain: If there is this variable in the current scope, it will be used, if not, it will be searched at the previous level.

focus :

        Closures can create an independent environment , and the environments in each closure are independent and do not interfere with each other. The closure will cause a memory leak. Every time the external function is executed, the reference address of the external function is different, and a new address will be recreated. However, if there is data referenced by the internal subset in the current active object, then at this time, this data will not be deleted, and a pointer will be reserved for the internal active object. [no answer]

shortcoming

        After the execution of the closure's containing function is completed, the scope chain of the execution environment of the closure's containing function will be destroyed, but the variables in the execution environment are still in memory;

        Freeing a variable requires setting the variable to null (eg let f = null ).

Guess you like

Origin blog.csdn.net/qq_42533666/article/details/129191271