Possible Duplicates:
What does this JavaScript snippet mean?
Location of parenthesis for auto-executing anonymous JavaScript functions?
(function(){
//something here...
})() <--//This part right here.
What exactly is this )()
?
What if I change it to this ())
?
(function(){
//something here...
}()) <--//Like this
That's simply an anonymous function. The
()
parens call the function immediately, instead of waiting for it to be called elsewhere.This is declaring an anonymous function and then immediately executing it. This is common for creating scoped variables.
It's an anonymous function that gets called immediately the () calls the function and there are ( and ) wrapping the whole thing.
This declares an anonymous function and calls it immediately.
The upside of doing this is that the variables the function uses internally are not added to the current scope, and you are also not adding a function name to the current scope either.
It is important to note that the parentheses surrounding the function declaration are not arbitrary. If you remove these, you will get an error.
Finally, you can actually pass arguments to the anonymous function using the extra parentheses, as in
See http://jsfiddle.net/eb4d4/
The first one just wraps the function in
(
)
so that it can call the function immediately with the()
Alerts Hi, while
Doesn't do anything since your function is never executed.
Its an immediately invoked anonymous function.
())
would not work because you need()
around the function before you can call it with ().Sorta equivalent to: