Offer to come, dig friends take it! I am participating in the 2022 Spring Recruit Punch card activity. Click here for details.

⭐ ⭐ ⭐

To answer this question, ask two questions:

  • How do closures come about?
  • What are closures for?

How do closures come about?

To understand how closures come about, you need to understand two concepts:

  • Scope and scope chain, inner functions always have access to variables declared in their outer functions.
  • The essence of a function is an object. The return value of a function can be a function.

In this example, the add function returns an anonymous function that, according to the rules of the scope chain, has access to the variable I defined by the add function.

function add () {
  let i = 0
  return function () {
    return ++i
  }
}

const fn = add()

console.log(fn()) / / 1
console.log(fn()) / / 2
Copy the code

The above example creates a closure, so what is the purpose of this closure?

What are closures for?

Closures are used to create a private variable of a function that will not be garbage collected as the function completes execution, extending the lifetime of the variable.

In the following example, variable I can be used as a private variable of the add function. After the add function executes, it is collected by the garbage collection mechanism, but variable I can still be accessed and modified.

If we tried to access fn. I directly from the global scope, we would get undefined, because I is a variable defined in the scope of function fn and is not a property of FN. Similarly, an error is reported if we try to access I, because I is not defined in global scope.

How do I view private variables in closures?

Make a breakpoint at the location of the internal function to view the private variables in the closure in the Sources panel of your browser.

To see two more private variables, I arbitrarily defined a name variable and an age variable.

Ok, so to summarize, closures are used to create private variables and prolong the period of those private variables that are not globally accessible.

Another way to understand closures

Closures can be understood as being closed, closed, or wrapping things up.

For example, I have $100 in secret money and I want to hide it from my wife.

I hid the $100 in a flowerpot, and the code looked something like this:

function flower () {
  const money = 100 // The money variable is completely hidden inside flower
  return function () {
    return money
  }
}

const fn = flower()
console.log(fn()) I know the way to find secret money

// I can't find my wife
console.log(money) Uncaught ReferenceError: Money is not defined

Copy the code

So the money variable is completely hidden inside the flower function, exposing only the flower pot,

On the other hand, my wife can only see a pot of flowers on the outside, and she can’t read the money variable on the inside anyway.

This is where closures are used, to hide variables as if they were secret money, to hide a bunch of variables from the outside world, but to access them in the form of a return function (my wife can’t find it, but I know how to get it).

And private house money is hidden all the time, won’t be collected by the wife, belong to myself, lengthened the use time of private house money (extended the life cycle of variable).

Is this analogy vivid enough to deepen your understanding of closures?

To deepen theA function is essentially an objectThe understanding of this sentence

As mentioned above, we implement closures by returning a function. There are other ways to implement closures, such as:

Define a parameter, assign an inner function to the parameter, and execute it externally.

let fn
function flower () {
  const money = 100
  fn = function () {
    return money
  }
}

flower()
console.log(fn()) / / 100
Copy the code

Use an array to store internal functions, push internal functions into the array, access the array externally and execute them.

function flower (arr) {
  const money = 100
  function fn () {
    return money
  }
  arr.push(fn)
}

const arr = []
flower(arr)
console.log(arr[0] ())/ / 100
Copy the code

Or you can store internal functions in an object, return the object, and access methods of the object externally.

function flower () {
  let money = 100
  function get () {
    return money
  }
  function add (num) {
    money += num
  }
  return {
    get,
    add
  }
}

const obj = flower()
console.log(obj.get()) / / 100
obj.add(100) // Put money into a flowerpot
console.log(obj.get()) / / 200
Copy the code

This way we can add an add method to our private money and put it into a pot regularly.

In fact, the fundamental reason you can implement closures in these ways is that functions are essentially objects, and functions have all the functions that objects have.

  • Functions can be assigned to variables
  • Functions can be added to arrays
  • Functions can be added as properties of objects
  • A function can be the return value of a function.

See this article for more information: why are JS functions called first-class citizens?

Different definitions of closures

We talked about the phenomenon and application of closures above, but we haven’t given a concrete definition yet.

In fact, I’ve seen a lot of different definitions of closures. For example:

  • MDN: A combination of a function bound (or surrounded by) references to its surrounding state (lexical environment) is a closure. That is, closures allow you to access the scope of an outer function within an inner function.

  • Little Red Book: Closures are functions that have access to variables in the scope of another function.

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

  • JS you didn’t know: Closures occur when a function can remember and access its lexical scope, even if the function is executed outside the current lexical scope.

  • Community: A closure is a collection of variables that an inner function refers to an outer function.

  • Community: the closure is just a binding the execution environment function, the function is not a simple expression of printed books, closure and common function, is the difference between it carries the execution environment, like people need to bring in the alien oxygen equipment, this function also with the environment in the process.

  • Community: A closure is an internal function that can access an outer scope, even after the outer scope has been executed.

  • .

Some people say that a closure is a phenomenon, some people say that a closure is a function, and some people say that a closure is a set of variables. Which one is true? !

In fact, they are both right. These definitions are similar and refer to the knowledge related to the execution process of a function, which can be understood in conjunction with the knowledge of execution context and scope.

To be honest, I think many of the definitions are very empty and difficult to understand after reading them. It is better to understand them with the specific examples mentioned above.

My personal favorite definition is that a closure is a collection of variables that an inner function refers to an outer function, after all it is tangible and can be displayed in the browser.

We don’t have to worry too much about the concept, because how you define a closure doesn’t affect how you actually use it, and just being able to say how closures come about and how they are used is enough to make the concept of closures clear.

As for the application of closures, Alin has encountered too many, temporarily sort out the following, later article slowly analysis:

  • The relationship between closures and the immediate execution function IIFE
  • Design a cache module with closures
  • Closures implement a singleton pattern
  • Closures and Currization functions, partial functions
  • Classic interview question: Loops and closures
  • How is WebPack modular packaging implemented with closures?
  • Closures used in class library encapsulation

At the end

Closure is JS learning this language anyway around not to snag, because of the application of the closure is in the world of our JS, if you look at it again this article didn’t read it, read it twice, those who learn front of classic books, such as “little red book”, “JS ninja techniques”, “you don’t know the JS”, he also recommend everyone to see.

Closures can be difficult for beginners, but if you’ve seen enough of them, you’ll understand them.

If my article is helpful to you, your 👍 is my biggest support ^_^

You can also follow the front End Daily Question column in case you lose contact

I’m Allyn, export insight technology, goodbye!

The last:

What is the execution context in “Front-end Daily Question (27)” JS?

Next up:

What is the execution stack in “Front-end Daily Question (29)” JS?