What is "closures"

Enclosure is a function that references free variables in the lexical context. An enclosure usually occurs when one function is declared within the body of another, and the inner function references local variables of the outer function. At runtime, when the outer function is executed, then an enclosure is formed, consisting of the code of the inner function and references to any variables within the outer function that the enclosure requires.

Utilizing

The closures are used to:

  • Software libraries can allow users to customize the behavior passing closures as arguments to functions important. For example, a function that classifies values can accept a closed argument that compares the values to be classified according to a criterion defined by the user.
  • Multiple functions can be produced in the same environment, allowing them to communicate confidentially.
  • Object systems can be built with closures. For example, Standard scheme does not support object-oriented programming, but there is object systems built for this programming language with recourse to closures.

Example

Javascript:

function novoContador () {
   var i = 0;
    return function ()  { // função anônima
      i += 1;
      return i;
   }
}

c1 = novoContador();
alert(c1());
alert(c1());
alert(c1());
alert(c1());
alert(c1());