Yes, wonderfully, there is the access to the variable scope. This is a very interesting phenomenon.
Your function makes perfect sense and actually works. To make it apparent, it's enough to uncomment
alert
:
function f() {
var value = Math.random();
function g() {
alert(value);
}
return g;
}
var g = f();
g()
I have no idea why you failed to see it; or perhaps you wanted to achieve something different, but then explain it.
It's harder to explain why this code works. The variable
value
is the local variable, it should not exist after the call to
f
. The trick works because JavaScript implements a very non-trivial effect,
closure which is one of the fundamental notions in programming, especially functional concepts. The fact that the variable is used in a function (also the object local to
f
context) which is returned. This is a kind of "double closure". First, the fact that
g
is returned expands the scope of
g
to outer scope. And then, the fact that
value
is used in
g
, expands the scope of
value
, too. Please read about it:
http://en.wikipedia.org/wiki/Closure_(computer_programming)[
^].
You can actually modify the code to obtain the value of the variable
value
on each call as a value returned from the function. Not that it makes any practical sense in this rudimentary example; it would be just another illustration of the closure effect.
In a way, through the effect of
closure a local object remains local in terms of visibility, but behaves like an outer scope object in terms of life cycle and indirect accessibility.
—SA