1, the closure

  1. Closures are functions that can read variables inside other functions
  2. A closure is a function that has access to variables in the scope of another function. The most common way to create a closure is to create another function inside a function and access local variables of this function through another function. Closures can be used to break through the scope of the scope.
  3. Closure features:
1, functions are nested within functions2Inner functions can refer to outer parameters and variables3, parameters and variables are not collected by the garbage collection mechanismCopy the code
  1. Closures:
1The main purpose of using closures is to design private methods and variables. The advantage of closures is to avoid contamination of global variables. The disadvantage is that closures are always in memory, which increases memory usage and can cause memory leaks if used improperly. In JS, functions are closures, and only functions have the concept of scope.2Closures are useful for reading variables inside functions and for keeping them in memory3Another benefit of closures is that they encapsulate the private properties and methods of an objectCopy the code

6. Pros and cons of closures:

Advantages: Encapsulation and caching can be implemented, avoiding global variable pollution. Disadvantages: Memory consumption, improper use may cause memory overflowCopy the code

7. Closure considerations:

  • Because closures cause variables in functions to be stored in memory, which can be very memory consuming, you should not abuse closures, which can cause performance problems for web pages and, in IE, memory leaks
  • The solution is to delete all local variables that are not in use before exiting the function