Example 1:
function Makecounter () { var i = 0; Console.log (++i);} var counter = Makecounter (); Output: 1counter (); Typeerror:undefined is not a functioncounter (); Typeerror:undefined is not a function
In this example, we declare a makecounter function and find var counter = Makecounter (); Output a result: 1 This is because the right makecounter () of the assignment number actually executes the function once, but there is no return value, so counter is given undefined, and the next two calls return an error typeerror:undefined I s not a function
Then look at the modified code:
Example 2:
function Makecounter () { var i = 0; return function () { console.log (++i); };} var counter = Makecounter; No output counter (); No output counter (); No output var counter2 = counter (); No output counter2 (); Output: 1counter2 (); Output: 2var Counter3 = Makecounter (); No output counter3 (); Output: 1counter3 (); Output: 2console.log (i);//REFERENCEERROR:I is not defined
This time the Makecounter function return value is a function, which is actually a closure, according to JavaScript advanced programming, the closure refers to a function that has access to variables in the scope of another function. Based on MDN:
Closures is functions that refer to independent (free) variables.
In other words, the function defined in the closure ' remembers ' the environment in which it is created.
It is usually the most common way to create a closure by creating a function inside a function like this.
A function in a closure can "remember" the active object that creates its outer environment, and after the Makecount function executes, its active object is not destroyed because the scope chain of the function within the closure still references the active object, and therefore remains in memory. From the point of view of garbage collection, the activity object of the external execution environment will not be treated as garbage collection.
As shown in the preceding code, it is worth noting that each time the Makecount function is called, the inner function body is the same every time the closure is returned, but each time it executes the active objects of the environment are independent and not related to each other, see the output of Count2 () and Count3 ().
It can be said that the functions in JavaScript are in closures because each function has access to the global execution environment outside the body of the function.
Understanding of Javascript closures