Possible Duplicate:
javascript function vs. ( function() { … } ());
Sorry if this is too basic, but what is this construct do?
(function MyFunction() {
/* Some codes ... */
})();
Maybe there is a special term for that? It can be useful for Googling, instead of just putting that snippet in the search field.
It’s called the direct invocation pattern. It defines an anonymous function, and then immediately executes it. This is useful for ‘private’ variables and such. If you’d normally do this:
there’d be a variable data in the global namespace and if someone entered
data = 123in a web console it could break your script. Using the direct invocation pattern, you can do this:In this case, the function getData will still exist in the global namespace, but data will be inaccessible from outside the closure namespace.
You’ll also notice MyFunction won’t exist in the global namespace when using this pattern. That is because of one of many small language rules, but basically a function is always available by it’s name inside the function. If you have something like this:
It works perfectly, and countToZero(5) will nicely return 5. But well, it’s not really nice if you use it in the non-global namespace, if this is used inside a function it’ll define countToZero as a member property of that function, which will break our return (as countToZero is no longer accessible through the global namespace)
This is not a realistic scenario perhaps, but it works for this example. Instead of the above code, we’ll use this:
This code is quite hard to break, except if you pass Infinity as the first param of course, even if you use it in completely ridiculous ways.
…
did I say I was going to provide clear explanation or nice, real-life examples? I hope I didn’t