Relearn basic knowledge, if there is not welcome correction, gratitude.

Closures are basically menstruation questions in interviews, so what exactly are closures?

What is a closure?

Closures occur when a function can remember and access its lexical scope. Even if the function is called outside the scope of the current function.

function foo() {let a = 1;
	function bar(){
		console.log(a)
	}
  return bar
}
letBaz = foo() baz() //1 closure copies codeCopy the code

Normally, scopes inside Foo are destroyed after foo() is executed (js’s garbage collection mechanism), and closures prevent destruction, so scopes inside Foo remain because bar() is still in the scope that references foo(). This reference is called a closure.

## What closures do

The main function is to implement module exposure

function Foo() {let something = 'cool'
  function doSomething() {return something
  }
  function doAnother(){
    ...
  }
    return {
      doSomething:doSomething,
      doAnother:doAnother
    }
}
letFoo = foo () // create module instance foo.doanother () // call the exposed method foo.dosomething () // call the exposed methodCopy the code

For example, when I write a module called Foo, I don’t want anyone to access my internal variables. I use exposed methods to access my internal variables.

Disadvantages of closures

Because closures prevent destruction scopes, they cause memory leaks. The function needs to be destroyed manually when it is not referenced.

function test() {
  var data = new Array(100000); 
  var getData = function(){returndata; };let a = setInterval(getData, 100); //clearInterval(a) manually destroy if not needed
}
Copy the code