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.

Now consider the following piece of code

Code Block
languagejs
titleexample js code
linenumberstrue
function makeFunc() {
  var name = 'Mozilla';
  function displayName() {
    alert(name);
  }
  return displayName;
}

var myFunc = makeFunc();
myFunc();

Line 6 returns a function name.  Like languages such as C and C++ using a function without the () yields the functions address, here it returns the a reference to the function that is then assigned to the variable myFunc at line 9.  The variable can then be used as function because once the RH value is assigned at line 9 the type of myFunc is assigned as a function reference. 

The reason this works is because all functions in javascript are closures.  closure is the combination of a function and the lexical environment within which that function was declared. This environment consists of any local variables that were in-scope at the time that the closure was created.