1. What are closures?

2. What do closures do?

Let’s start with a quick overview: What is a closure?

function foo() {

  var a = 2    
  
  function bar() { 
    console.log(a);
  }
  
  bar()
  
}

foo()

Copy the code

In the above code, function foo is executed, and function bar is defined and executed. The function bar has access to variable A

This is a closure: the sum of the “function” and the “variables accessible within the function” (also known as the environment) is a closure

Which brings us to the second question: What do closures do?

Closures are often used to “indirectly access a variable.” Or, “Hide a variable.” Suppose in a payment application, we need to define the total amount of money the user currently has. This number needs to be accessed in many places. Instead of closure, maybe we can use a global function?

window.money = 4396.00
Copy the code

It doesn’t look right. What if someone with bad intentions changes the number to 7 or 7777777?

So we can’t let anyone directly access this variable, so we’re going to have to use local variables.

It is difficult for others to change this quantity just by using local variables. What should we do?

We can use closures to expose a function and implement a common variable

Borrow nguyen other teacher here in closure the example in the article (www.ruanyifeng.com/blog/2009/0…

 function f1(){var money=999; moneyAdd=function(){money+=1}function f2(){alert (money); }returnF2; }varResult = f1 (); result();/ / 999MoneyAdd (); result();/ / 1000
Copy the code

The value of the first reference to the result function is 999, and the value of subsequent references to the result function is 1000.

At this point, the result function is actually the closure function F2, and the change of result value indicates that money has become a “global variable”, which does not disappear after f1 is referenced, but is stored in some memory and will not be collected by garbage collection after the call.

extension

Defects in closures

Closures cause a certain amount of memory leakage: every major browser has a JS execution engine with a recycle mechanism that periodically removes unnecessary jumpy data. However, the reclamation mechanism cannot reclaim the closure’s functions or the data stored in the closure’s functions. This leads to more performance overhead for the browser.

Other uses of closures

1. Do cache, so that multiple functions can act on an object at the same time 2. Implement encapsulation, so that attributes can be privatized 3. In modular development, it prevents contamination of global variables