Closure is a very important feature of JavaScript, which means that the current scope can always access variables in the external scope. Because a function is the only structure with its own scope in JavaScript, the creation of a closure depends on the function.
Closure is a very important feature of JavaScript, which means that the current scope can always access variables in the external scope. Because a function is the only structure with its own scope in JavaScript, the creation of a closure depends on the function.
Simulate private variables
function Counter(start) { var count = start; return { increment: function() { count++; }, get: function() { return count; } }}var foo = Counter(4);foo.increment();foo.get(); // 5
Here, the Counter function returns two closures: The increment function and the get function. Both functions maintain reference to Counter in the external scope, so you can always access the variable count defined in this scope.
Why cannot I access private variables externally?
Because JavaScript cannot reference or assign values to the scope, it is impossible to access the count variable externally. The only way is through the two closures.
var foo = new Counter(4);foo.hack = function() { count = 1337;};
The above Code does not change the value of the count variable defined in the Counter scope, because foo. hack is not defined in that scope. It will create or overwrite the global variable count.
Closure in Loop
A common error occurs when the closure is used in the loop. Suppose we need to call the loop serial number in each loop.
for(var i = 0; i < 10; i++) { setTimeout(function() { console.log(i); }, 1000);}
The code above will not output numbers 0 to 9, but will output numbers 10 times.
When console. log is called, the anonymous function keeps referencing the external variable I. At this time, the for loop has ended and the I value has been changed to 10.
To get the expected result, you need to create a copy of variable I in each loop.
Avoid reference errors
In order to obtain the cyclic sequence number correctly, it is best to use the anonymous wrapper (note: we generally call self-executed anonymous functions ).
for(var i = 0; i < 10; i++) { (function(e) { setTimeout(function() { console.log(e); }, 1000); })(i);}
External anonymous functions are executed immediately and I is used as its parameter. In this case, the e variable in the function has a copy of I.
When the anonymous function passed to setTimeout is executed, it has a reference to e, and this value will not be changed cyclically.
Another way to do the same is to return a function from the anonymous package. This is the same as the above Code.
for(var i = 0; i < 10; i++) { setTimeout((function(e) { return function() { console.log(e); } })(i), 1000)}
The above is the JavaScript advanced series-closure and reference content. For more information, see the PHP Chinese website (www.php1.cn )!