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

What's the use of closures ?

  • You can use a closure to associate some data with a function that operates on that data, anywhere you may use an object with some properties and a method operating on those properties.
  • Closures allow you to create private members: there no way to make object's properties private in JavaScript. With closures, variables in the function scope become private members of the function, because they can only be accessed by the closure.

Example 2: closure with a parameter

Example 3: more closures sharing data
You can have two or more nested functions to be defined within the same outer function and share the same scope chain

No comments :

Post a Comment