Sonntag, 8. Juni 2014

Have a Javascript closure!

A closure is an important feature of the Javascript language. Basically a closure is an inner function that has access to the outer (enclosing) function’s variables. In other words, the function defined in the closure 'remembers' the environment in which it was created.
Consider the following outer function (initNames) containing an array (names) and an inner function (pushName):
function initNames(){
  var names = []
  function pushName(name){
    if(name.length > 0) names.push(name)
    alert(names.join(', '))
  }
  return pushName
}
Calling initNames initializes the array names and defines the function pushName in the scope of its enclosing function initNames and returns the same. That inner function pushName expects one parameter for pushing it into the names array (if it is not blank) and alerts all stored names.
The closure pushName can be used like:
$(document).ready(function(){
  var pushName = initNames()
  $("#20140608").click(function(event){
    var textInput = $(this).prev()
    pushName( textInput.val() )
    textInput.val('')
  })
})
and the HTML:


After the DOM was loaded, the defining function initNames returns the closure and assigns it to the variable pushName. And that is the key point. While initializing the closure, it has three scope chains:
  1. it has access to its own scope (variables defined between its curly brackets)
  2. it has access to the outer function’s variables
  3. it has access to the global variables
Furthermore a click event is observed to the button, which picks the input value and assigns it to the closure function pushName.
Try it out yourself:

Although only the inner function pushName was called, it has access to its outer function's variables.

Further articles of interest:

Supported by jQuery 1.10.2