Sunday, November 29, 2015

JavaScript Closures

Variable scope:

  • scoping is how you search for a variable
  • the scope of a variable is the area where that variable can be accessed by name

JavaScript language has lexical scope also known as static scope:

  • JavaScript do variable lookup in the scope in effect when a function is defined: the textual arrangement of its definition
  • functions are executed in the variable scope in effect when they were defined

Nested function closures

  • the nested function's scope chain in effect when the function is defined is still in effect when the function is invoked out of the outer function
  • functions are called closures because they close around their local variables

Example 1: lexical scope for a closure