Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
Take what you have learned about the scope chain and scope lookup in
this chapter, and a closure should not be overly complicated to
understand. Below, we create a function called countUpFromZero. This function actually returns
a reference to the child function contained within it. When this child
function (nested function) is invoked, it still has access to the parent
function’s scope because of the scope chain.
<!DOCTYPE html><html lang="en"><body><script>
var countUpFromZero = function() {
var count = 0;
return function() { /* return nested child function when countUpFromZero is
invoked */
return ++count; // count is defined up the scope chain, in parent function
};
}(); // invoke immediately, return nested function
console.log(countUpFromZero()); // logs 1
console.log(countUpFromZero()); // logs 2
console.log(countUpFromZero()); // logs 3
</script></body></html>