The basic concept

Closures allow functions to access and manipulate variables outside the function.

Closures are functions that have access to variables in the scope of another function.

Closures are functions that can access free variables.

Closures are functions that have access to variables in the scope of another function

How do closures form

An internal function that has a reference to an external scope causes a closure. There is an example of a closure from the concept of superscope introduced above: return F is a representation.

Protection of the execution environment by lexical scope

Javascript scopes have two parts: lexical scope and dynamic scope

The former is static, for example

var x = 1 var fn function a() { var y = 1 function b() { var z = 2 console.log(x, Y,z)} fn = b} x,y,zCopy the code

Hiding the secrets of landmines

Function createMine() {const s = 'createMine'} function mine() {console.log(s)}Copy the code

There’s a tunnel warfare story that comes to mind. Let’s say we don’t want the secret of the mine to be exposed to the enemy, so we want to keep the secret of the mine inside the factory. But I hope you build a mine that uses the secrets of land mines. I wonder if this is the time we need to figure something out.

So let’s summarize briefly what we need is

  • Local variables in the factory function createMine cannot be accessed externally
  • Mines can access local variables so that they have maximum impact

Function as the return value

Return function() {console.log(s)}} const m = createMine() m()Copy the code

The first is that the factory function will return an anonymous function. Thus, according to scope rules, anonymous functions can indeed call the scope of the factory function createMine. The local variables of createMine cannot be accessed directly by any external functions.

Function as argument

Const b = [] function createMine(b) {const s = 'createMine' b.ush (function() {console.log(s)})} createMine(b) b[0]()Copy the code

Another way to do this is not to return a value, but to use a parameter.

scope

Const mine function createMine(b) {const s = 'createMine' mine = function() {console.log(s)})} createMine() mine()Copy the code

Another way to do this is not to return a value, but to use a parameter.

The interview guide

  • Say why closures occur, and don’t think of loop traps as closures.

review

  • Closures are a must-have topic, but they’re not used in business development, so they’re especially hard to remember. It’s kind of like bouncing a ball in football. That’s all it takes to test a professional’s ability, but most amateurs are useless on a wild pitch.

\