Closures and possible problems caused by closures

What is closure:

The function's scope and all its variables are destroyed after the function execution ends. However, after creating a closure, the scope of the function will be saved until the closure no longer exists.

In JavaScript, if an object is no longer referenced, the object will be recycled by the garbage collection mechanism.

The role of closure:

1. You can read the variables inside the function

2. Keep the values ​​of these variables in memory.

Possible problems caused by closures:

  1. Closures will cause the variables in the function to be stored in memory, which consumes a lot of memory, so closures cannot be abused, otherwise it will cause performance problems on the web page.

  2. Generally speaking, when the function completes execution, the local active object will be destroyed, and only the global scope will be saved in the memory. However, the situation with closures is different. After the closure function is executed, its active object will not be destroyed because the scope chain of the anonymous function still refers to the active object. The closure function's active object will not be destroyed until the anonymous function is destroyed.

https://blog.csdn.net/weixin_42153287/article/details/125582993

Guess you like

Origin blog.csdn.net/qq_39813400/article/details/129060978