Simulating private variables
Why can’t private variables be accessed externally
Closures in loops
Avoid reference errors
Closure is a very important feature of JavaScript, which means that the current scope can always access the outer scope Variables. Because functions are the only constructs in JavaScript that have their own scope, closure creation relies on functions.
Simulating 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 function increment and the function get. Both functions maintain a reference to the outer scope Counter, so they can always access the variable count defined within this scope.
Why private variables cannot be accessed externally
Because scope cannot be referenced or assigned in JavaScript, there is no way to access the count variable externally. The only way is through those two closures.
var foo = new Counter(4); foo.hack = function() { count = 1337; };
The above code will 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.
Closures in loops
A common mistake occurs when using closures in loops, assuming we need to call the loop sequence number in each loop
for(var i = 0; i < 10; i++) { setTimeout(function() { console.log(i); }, 1000); }
The above code will not output the numbers 0 to 9, but will output the number 10 ten times.
When console.log is called, the anonymous function keeps a reference to the external variable i. At this time, the for loop has ended and the value of i has been modified to 10.
In order to get the desired result, a copy of variable i needs to be created in each loop.
Avoid reference errors
In order to obtain the loop sequence number correctly, it is best to use an anonymous wrapper (Translator's Note: In fact, it is what we usually call self-execution anonymous function).
for(var i = 0; i < 10; i++) { (function(e) { setTimeout(function() { console.log(e); }, 1000); })(i); }
The external anonymous function will be executed immediately and takes i as its parameter. At this time, the e variable in the function will have 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 by the loop.
There is another way to accomplish the same job, and that is to return a function from an anonymous wrapper. This has the same effect as the code above.
for(var i = 0; i < 10; i++) { setTimeout((function(e) { return function() { console.log(e); } })(i), 1000) }
The above is the content of JavaScript advanced series - closures and references. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!