The first times you see a JavaScript closure at work, you could get lost in the code, but being it such a common paradigm, you are going to get used to it in almost no time:
var sequence = (function() { // 1 var current = 0; // 2 return function() { // 3 return current++; } }()); // 4 for(var i = 0; i < 3; ++i) console.log(sequence());1. We define as a variable as ... what? There's an anonymous function definition starting here, and if we jump to (4) we see that the function is invoked just after being defined.
2. In the function body we see a local variable definition, that results being private to the function. No way anyone outside could see or modify it.
3. And here we see what our anonymous function returns: another function! This internal function does the dirty job of post-incrementing the current sequence number and returning it.
4. This means that JavaScript has to invoke the anonymous function, that returns the internal function, that returns - when called - the sequence number.
A bit contrived, isn't it? But the good news is that now we can simply call our "sequence" variable to increase and get the sequence number, exactly in the same way we called the original sequence generator. And, as required, its internal status is not visible anymore from outside.
No comments:
Post a Comment