当前位置:网站首页>A simple understanding of closures

A simple understanding of closures

2022-06-11 16:59:00 The mighty moon

Closures open a channel for accessing the internal scope of a function outside the function , Normally, the scope variables inside the function cannot be accessed outside the function .

The representation judges whether it is a closure :

1. Function nested function

2. Internal functions are return

3. The inner function calls the local variable of the outer function

Application scenarios :

1.  Function as return value

    function fn() {
      var count = 1

      function fn2() {
        console.log(count)
      }
      // Returns a function , This function is a closure 
      return fn2
    }

    //f1  Namely  box  function 
    var f1 = fn()

    //5 Call... In seconds f1 function , Can still print count Value ,  Closures allow local variables to reside in memory 
    setTimeout(function () {
      f1()
    }, 5000)
    function fn() {
      var count = 1

      function fn2() {
        count += 1

        return count
      }

      return fn2
    }

    var f1 = fn()

    console.log(f1())
    console.log(f1())

2. The function is passed as an argument ( Callback function )

原网站

版权声明
本文为[The mighty moon]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206111653596163.html