Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.


Info
titleinfo

My home for all the weirdities of javascript

...

According to MDN (Mozilla Developers Network) info on Closures, "closures are functions that refer to independent (free) variables (variables that are used locally, but defined in an enclosing scope). In other words, these functions 'remember' the environment in which they were created."

So the following piece of code demonstrates this quite nicely

...

The function displayName() declared at line 3 is a closure, notice that it has access to it's enclosing environment.  When you run this code, the alert displays the message "Mozilla".  The function displayName() is able to access the variable name (line 2) because of what javascript terms lexical scoping, which describes how a parser resolves variable names when functions are nested. The word "lexical" refers to the fact that lexical scoping uses the location where a variable is declared within the source code to determine where that variable is available. Nested functions have access to variables declared in their outer scope.