The basic idea is that global variables are evil. This technique
moves what would otherwise be global variables into a closure [1],
As to how closures manage to keep the global namespace clean, you will
need to read up on closures. [1]
Cheers,
-- Scott
You might want to read up on closures too. Using that syntax discussed
doesn't automatically create a closure. A closure is only created if it
returns a reference to a variable or function. A closure is where a
reference is kept to something that might otherwise have been destroyed
or garbage collected but is kept alive due to the external reference to
it. Well, that's how I understand them anyway.
Well, technically and by the specification every (FD, FE, NFE and even
created directly via Function constructor) function in ECMAScript is a
closure. On implementation level however some optimization can be
made: if scope chain doesn't contain free variables, maybe local
variable can be stored in sort of stack-based system (which is faster)
rather than in heap (which is slower, but this is the way for
closures, as the idea of closures cannot be applied in stack-based
systems).
Also, some implementations, for example one of versions of DMDScript
doesn't have closures at all (there every internal returned function
will be strictly equal to the function return from the second call of
parent function - just like they joined objects, but in deed - this
implementation of ES doesn't have closures).
So closures in ECMAScript are:
1) from the theoretical viewpoint: *all* functions regardless
function's type;
2) from the practical viewpoint: functions which (a) have free
variables and (b) live longer than context in which they were created.
If you interesting in theory of closures (about the reasons for
creating the idea of closures, such as "Funarg" and so on): <URL:
"
http://javascript.ru/blog/Dmitry-A.-Soshnikov/Tonkosti-ECMA-262-3.-
CHast-6.-Zamykaniya."> (online translator from Russian is needed).
/ds