Closures#

Python#

JavaScript#

viele Antworten auf:

http://stackoverflow.com/questions/111102/how-do-javascript-closures-work

beste Antwort:

http://sleeplessgeek.blogspot.com/2009/12/so-what-are-these-closure-thingys.html

Beste Antwort#

Closures are a way to let a function have persistent, private variables - that is, variables that only one function knows about, where it can keep track of info from previous times that it was run.

The following simple example covers all the main points of JavaScript closures.

Here is a factory that produces calculators that can add and multiply:

function make_calculator() {
  var n = 0;  // this calculator stores a single number n
  return {
    add : function (a) { n += a; return n; },
    multiply : function (a) { n *= a; return n; }
  };
}

first_calculator = make_calculator();
second_calculator = make_calculator();

first_calculator.add(3);                   // returns 3
second_calculator.add(400);                // returns 400

first_calculator.multiply(11);             // returns 33
second_calculator.multiply(10);            // returns 4000

The key point: Each call to make_calculator creates a new local variable n, which continues to be usable by that calculator’s add and multiply functions long after make_calculator returns.

If you are familiar with stack frames, these calculators seem strange:

How can they keep accessing n after make_calculator returns? The answer is to imagine that JavaScript doesn’t use „stack frames“, but instead uses „heap frames“, which can persist after the function call that made them returns.

Inner functions like add and multiply, which access variables declared in an outer function**, are called closures.

That is pretty much all there is to closures.

Wikipedia#

In computer science, a closure is a function together with a referencing environment for the nonlocal names (free variables) of that function.