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);
Built on Simply Works Core
Powered by WordPress
Copyright © pedant.dk
I hack on things that lets you find stuff.
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
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'.
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);
Where did my indentation go dammit!