closure

Closures are functions.

A closure is a function that has access to variables in the scope of another function.

A scope can access local variables inside another function. The function of the accessed variable forms a closure.

1 Closure definition

  • Closures occur when nested inner functions reference variables of external functions.

  • Using chrome tools, closures are essentially an object in an internal function that contains referenced variable properties.

Key functions of closures

  • Extends the scope (life cycle) of variables.

  • Allows the outside of a function to manipulate local variables inside.

  • Protects variables from external contamination and keeps them in memory.

  • Write a closure.

    function fn1() {
      var a = 2;
      function fn2() {
        a++;
        console.log(a);
      }
      return fn2;
    }
    var f = fn1();
    f();	/ / 3
    f();	/ / 4
    Copy the code

Closure application

  • Modularity: Encapsulate some data and the functions that manipulate it, exposing some behavior.

  • Loop through plus listen.

  • The JS framework (jQuery) makes extensive use of closures.

4 faults

  • Variables may occupy too much memory.
  • Memory leaks may occur.
  • Solution:
    • F = null; // make the internal function object junk.