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:
- Can prevent variables from being recycled by GC (here I often ask a question: Can you introduce the implementation mechanism of GC? )
- 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:
- When sys/wait.h, it will generate an independent scope
- Objects in the same scope can access each other
- 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.