What is a closure?

  • ✅ A closure is a function that has access to a variable in the scope of another function.
  • ✅ MDN: Closure is a special kind of object. It consists of two parts: the function and the environment in which the function is created. The environment consists of any local variables that were in scope when the closure was created.
  • ✅ Self-understanding: The mechanism for executing functions, forming private contexts, and saving and protecting private variables, called closures, is a mechanism.

The execution of a function looks at closures

process

  1. Forming a private context
  2. Into the stack perform
  3. Some column operations
    1. Initialize the scope chain (both ends < current scope, upper scope >)
    2. Initialize this
    3. To initialize the arguments
    4. Assign a value parameter
    5. Variable ascension
    6. Code execution
      1. If a variable is not private, search it on the scope chain. If it is not superior, search it online until EC(G). The search of a variable is actually a process of stitching the scope chain.
  4. Normally, after code execution is complete, the private context is reclaimed from the stack. However, in special cases, if something in the current private context is occupied by something other than the execution context, the current private context will not be released from the stack, that is, an undestroyed context, closure, is formed.

Three of the following

  • If something in the current context is occupied by something outside the context, the current context will not be released.
  • If it is not occupied, it is released as soon as the execution is complete.
  • In addition to the above two cases, there is also a case where the context is not used, but the next time it is used, so it cannot be released until it is used up, so it forms a temporary not released.

Each execution of a function creates a new private context, not necessarily related to the context generated by the previous execution

The role of closures

Function execution creates a new private context, which may or may not be released. This context does what it does:

  1. Protection: A separate area of code execution where private variables can be stored without any conflicts with other areas (to prevent global variable contamination)
  2. Save: If the context is not destroyed, the value of the stored private variable is not destroyed and can be retrieved and used in its subordinate context

In the market, it is generally considered a closure only if the resulting private context is not freed (because if it is freed, the previous one is gone); Others argue that a closure is only a low-level context that uses the action in that context;

exercises

let x = 5; const fn = function fn(x) { return function(y) { console.log(y + (++x)); } } let f = fn(6); f(7); // 14 fn(8)(9); // 18 f(10); // 18 console.log(x); / / 5Copy the code
  1. Variable promotion (skip, no var, function…)
  2. Code execution
    1. x -> 5

    2. fn -> 0x 001

    3. The fn (6) function executes

      1. Create private context, create active object AO(fn1)
      2. Initialize the scope chain, <

        >
        (fn1),>
      3. Initialize this
      4. To initialize the arguments
      5. Parameter value
      6. Variable ascension
      7. Function executes, returns a small function for which new heap memory is created to store function contents (scope, code string, key-value pair)
    4. The small function returned by f =, that is, the new function execution, f -> 0x 002, because 0x 002 is occupied by F, its context (scope) cannot be freed.

    5. F (7) is executed

      1. Create private context, create active object AO(f1)
      2. Initialize the scope chain, <

        >
        (f1),>
      3. Initialize this
      4. To initialize the arguments
      5. Parameter value
      6. Variable ascension
      7. X = 6, y +(++ x) = 14 in EC(fn1)
    6. The fn(8) function executes

      1. Create private context, create active object AO(fn2)
      2. Initialize the scope chain, <

        >
        (fn2),>
      3. Initialize this
      4. To initialize the arguments
      5. Parameter value
      6. Variable ascension
      7. Function executes, returns a small function for which new heap memory is created to store function contents (scope, code string, key-value pair)
    7. The fn(8)(9) function executes

      1. Create private context, create active object AO(F2)
      2. Initialize the scope chain, <

        >
        (f2),>
      3. Initialize this
      4. To initialize the arguments
      5. Parameter value
      6. Variable ascension
      7. X = 8, y +(++ x) = 18, y +(++ x) = 18
    8. F (10) is executed

      1. Create private context, create active object AO(f3)
      2. Initialize the scope chain, <

        >
        (f3),>
      3. Initialize this
      4. To initialize the arguments
      5. Parameter value
      6. Variable ascension
      7. X = 7, y +(++ x) = 18 in EC(fn1)

Let’s look at an example, and see if you can figure out the answer by following the idea of the last example.

let a = 0, b = 0; let A = function(a) { A = function (b) { console.log(a + b++); } console.log(a); } A(1); // 1 A(2); / / 3Copy the code

How to answer closure questions in an interview

In fact, there are many closure questions in the interview, including written tests and q&A. In addition, the interview may not directly ask closure, but ask other questions, but may use closure.

In the interview, if it is the written test of the above exercises or see the code to say the results of the problem, it can refer to the above ideas, this kind of topic no matter how complex, million change from its case.

If the interview is a q&A, don’t just answer the concept of closures. Also learn to answer closures from a theoretical, underlying mechanism, and practical perspective to see not only the depth of your base capabilities, but also the breadth of your base capabilities. I have a deeper understanding of the challenges in my previous article “Four Closures” that amazed interviewers | More articles in August

  1. So what is a closure?
  2. When talking about function creation and execution look at closures (quote: stack, EC, AO, VO, scope)
  3. Then I’ll talk about what closures do and how they are referenced in projects, and the problems they pose
  4. Finally, how to use the advanced programming skills triggered by closures in the framework source code, or write your own class library

conclusion

Closures are a common scenario both in daily development and in interviews, and a good understanding of them will help you in both.