Possible Duplicate:
开发者_如何学JAVA JavaScript: Why the anonymous function wrapper?
Sometimes I see a structure like this in JS programs:
(function() {
// blah blah
})();
Any ideas what's this doing and what are its side-effects and benefits?
It's to create a new scope (to avoid polluting the parent one). Surprisingly (to beginners familiar with C-like languages), JavaScript does not create a new scope when you use braces alone:
{
var a = "foo";
}
// a still == "foo".
(function() {
var b = "bar";
})();
// b doesn't exist.
However, functions always create a new scope. Thanks to JavaScript's closures, existing variables from the parent scopes are automatically brought (closed) into the anonymous function. So in cases (like in the question) where the anonymous function is used nowhere else (since it's never assigned), it basically acts like a C-style brace.
Unlike many other curly-brace-delimited languages, JavaScript does not scope variables to the nearest enclosing block. Instead, var
statements scope variables to the enclosing function. A common mistake among JavaScript programmers is to declare var
s inside a loop or conditional with the assumption that they will go out of scope upon the end of the block.
Creating an anonymous function, and then executing it immediately (by placing the ()
after it) causes a new scope to be created, ensuring that variables declared within wil not interfere with other JavaScript that may be hanging around. Wrapping the entire thing in another set of parens makes it an expression, which can resolve some syntax ambiguities for maximum browser compatibility.
It prevents pollution of the global namespace. That is, identifiers won't leak out to the rest of the page/code/script.
精彩评论