On Oct 29, 6:46 am, vunet <vunet...@gmail.comwrote:
It has been widely used nowadays to wrap JavaScript libraries, as seen
in JQuery.
(function() {
var global = this;
// ...
})();
The advantage, as I learned, is the isolation from other global
variables. But how? What other advantages does this wrapper have. For
example, I have my library as:
Here's a concrete example: Imagine that you have some functions to
declare, *and*
some code that you want to be executed, e.g.:
function x() {
// Do something
}
function y(a) {
// Do something else
}
function untilSometime() {
x();
if ((now.getTime() + 1000) < (new Date().getTime())) {
y();
} else {
clearInterval(ihandle);
}
}
var now = new Date;
var ihandle = setInterval(untilSometime,100);
The result is that "x", "y", "untilSometime", "now", and "ihandle" are
all
global properties. There's a possibility that any of them have
overwritten
pre-existing properties with the same names, as well as the
possibility that
they'll be overwritten by code later in the document. Wrapping the
whole
thing in an immediately executed function expression makes all those
local
to that function, and avoids both those problems; and produces the
desired
effect without creating -any- global properties.
--
hj