Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

7. Scope and Closures > Closures Are Caused by the Scope Chain

Closures Are Caused by the Scope Chain

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.

Live Code

<!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>

  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint