closures -oh yeah?

Hvad mon der sker her :


var a=1;
function foo() {
var a;
function bar() {
a=2;
return a;
}
return bar;
}

a=3;
var b=foo();
var c=b();
alert(c);
alert(a);

5 comments

  1. Mike Peat says:

    The second alert will return whatever "a" has been set to most recently… but which "a"? The global one declared at the top, because the other one is local to the function foo and only exists while that is executing. So the line "a=3;" is that most recent assignment, so the second Alert pops-up "3".

    The first alert is more complicated. It shows the value of "c". "c" is assigned to the returned value from "b()" and b has been assigned to "foo()". foo() in turn returns the *function* "bar", so "b" is "bar", so "b()" is "bar()" (NOT foo(), BTW.) "bar()" assigns 2 to the local variable "a" of foo and then returns it (it could be anything – it is what it returns that counts, that it is a is a distraction!), so "c" contains (has the value of) the return from "bar()", so the first Alert ("Alert(c)") pops-up "2".

    Mike

  2. Jakob Kruse says:

    Var det et oprigtigt spørgsmål?

    Der erklæres to variabler ved navn 'a', én i global kontekst og én i kontekst af funktionen 'foo'. Den globale 'a' initieres til værdien 1, men rettes umiddelbart efter erklæringen af 'foo' til 3. Så kaldes 'foo', som returnerer en funktion der piller ved værdien af den lokale a og i øvrigt returnerer 2. Denne returnerer funktion kaldes, og returværdien (altså 2) gemmes i 'c'. Til sidste udskrives 'c' (2) og 'a' (3).

    Et forholdsvis trivielt eksempel på closures i øvrigt, der kun spiller ind her ved at det 'a' der refereres til fra 'bar' funktionen, altid er den der er erklæret i 'foo'.

  3. Mike Peat says:

    IMO, more fun is this, which demonstrates the closure even more clearly and uses a lambda as well::

    var a=1;
    var b = function() {
    var a;
    return function() {
    a=2;
    return a;
    };
    }();
    a=3;
    var c=b();
    alert(c);
    alert(a);

  4. Harm Wibier says:

    :D First will do 2 and the second will do 3… think this is a great example of why one shouldn't use closures to much ;)

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>