Home > Article > Web Front-end > [JavaScript] Understand closures in seconds
Although closures are a fundamental idea in JavaScript, newcomers may find them vague and challenging to grasp. Specifically, the ECMA standard's definition can be challenging to comprehend without any real-world experience. As a result, rather than going into great length to explain the notion of closures in this post, we will make it easy for you to comprehend by using actual code.
function A(name){ function B(){ console.log(name); } return B; } var C = A("Closure"); C();//Closure
This is the simplest closure.
Now that we know the fundamentals, let us briefly examine how this differs from a typical function. The following is how the aforementioned code appears when translated into natural language:
One statement can encapsulate these five operations:
Function B inside function A and variable name are referenced by variable C outside function A.
With a little modification, this statement defines a closure as follows:
When an inner function is referenced by a variable outside the outer function, a closure is formed.
Therefore, performing the above five operations defines a closure.
Before we understand the uses of closures, let's understand JavaScript's GC (Garbage Collection) mechanism.
In JavaScript, when an object is no longer referenced, it will be reclaimed by the GC, otherwise, it will continue to be kept in memory.
In the above example, B depends on A because B is defined within A, and A is indirectly referenced by C because the external variable C references B.
That is, A will not be collected by the GC and will continue to be kept in memory. To prove this reasoning, let's slightly improve the above example.
function A(){ var count = 0; function B(){ count ++; console.log(count); } return B; } var C = A(); C();// 1 C();// 2 C();// 3
Why is count not reset?
Closure mechanism:
Thus, if you define some variables in a module and want to keep these variables in memory but not “pollute” the global variables, you can define this module using closures.
The above is the detailed content of [JavaScript] Understand closures in seconds. For more information, please follow other related articles on the PHP Chinese website!