Closure generation

  • A closure is generated when a nested inner function references a variable (function) of a nested outer function
    function fn1() {
      var a = 1
      var b = 2
      function fn2() { 
        console.log(a) // The closure refers to a, so there is a variable a in the closure
      }
    }
    fn1()
Copy the code

Common closures

  • Take a function as the return value of another function
    function fn1() {
      var a = 2
      function fn2() { 
        a++
        console.log(a)
      }
      return fn2
    }
    var f = fn1()
    f() / / 3
    f() // 4 Only one closure is generated because it is executed
Copy the code
  • Pass a function as an argument to another function call
    function fn1(msg, time) {
      setTimeout(function () {
        console.log(msg)
      }, time)
    }
    fn1(1.2000)
Copy the code

The role of closures

  • Make variables inside a function live in memory after the function is executed (extends the life of local variables)
  • Make it possible to manipulate (read and write) data (variables/functions) from outside the function into the function itself

The life cycle of closures

  • produce
    • Generated when the nested internal function definition completes execution (not when called)
  • death
    • Dies when a nested internal function becomes a garbage object
    function fn1() {
      var a = 2 // The closure has been generated
      function fn2() { 
        a++
        console.log(a)
      }
      return fn2
    }
    var f = fn1()
    f() / / 3
    f = nul // The closure dies
Copy the code