At the front of the interview, when the interviewer asks you about your understanding of closures, how do you answer it

  javascript, question

I am often asked this question. The current situation is to give me something that I know is a closure, but let me say what is a closure, and I say it is not very good. When the interviewer asks this question, how should I answer it will look more bright. Thank you ~

As an interviewer, I don’t want to hear most of the answers upstairs, such as:

  1. Can prevent variables from being recycled by GC (here I often ask a question: Can you introduce the implementation mechanism of GC? )
  2. You can implement certain features, such as private variables

These are the results of closures, or the use of closures, not closures themselves. These usages and phenomena can be deduced through closure mechanism. In addition, closures are very important in JS inside, and I think it is still necessary to understand them clearly.

JS’s closure contains the following key points:

  1. When sys/wait.h, it will generate an independent scope
  2. Objects in the same scope can access each other
  3. The scope is in a hierarchical inclusion state, forming a scope chain. Objects in the child scope can access objects in the parent scope, otherwise they cannot. In addition, the child scope uses the object of the nearest parent scope.

In fact, the second point is the true closure, but we usually extend the concept of “closure” to the sum of the above three points. Based on these three points, other usage and problems can be introduced.


In addition, on the issue of garbage collection, “JS Advanced Programming” has a relatively clear introduction. Closures do not cause memory leaks, just as we cannot say kitchen knives kill people. Therefore, it is suggested that everyone should understand GC, why closures may sometimes cause memory leaks, and how to deal with them? Which browsers will happen and which will not, so it is easier to write your own code. After all, all JS contain closures.