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 > Scope Is Determined During Function Definition, not Inv...

Scope Is Determined During Function Definition, not Invocation

Since functions determine scope and functions can be passed around just like any JavaScript value, one might think that deciphering the scope chain is complicated. It is actually very simple. The scope chain is decided based on the location of a function during definition, not during invocation. This is also called lexical scoping. Think long and hard about this, as most people stumble over it a lot in JavaScript code.

The scope chain is created before you invoke a function. Because of this, we can create closures. For example, we can have a function return a nested function to the global scope, yet our function can still access, via the scope chain, its parent function’s scope. Below, we define a parentFunction that returns an anonymous function, and we call the returned function from the global scope. Because our anonymous function was defined as being contained inside of parentFunction, it still has access to parentFunction’s scope when it is invoked. This is called a closure.


  

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