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:
// global namespace
var data = 'lol';
function getData() {
return data;
}
there'd be a variable data in the global namespace and if someone entered data = 123 in a web console it could break your script. Using the direct invocation pattern, you can do this:
// global namespace
/*lotsofcodehere*/
(function MyFunction() {
// closure namespace
var data = 'lol';
this.getData = function getData() {
return data;
}
})();
// global again
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:
// returns the amount of from--s needed to get to 0 :D
// (yes, it returns it's input number :D)
(function() {
var i = 0, keep = false;
this.countToZero = function(from) {
if(from === 0) {
keep = false; // don't keep i's contents on next invocation
return i;
}
if(!keep) i = 0; // reset i on first invocation
i++;
keep = true;
return countToZero(from - 1);
}
})();
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:
/*code*/
this.countToZero = function countToZero(from) {
// countToZero will *always* exist here as a reference to this function!
/*code*/
return countToZero(from);
};
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
It creates and executes the function MyFunction without placing it on the global namespace. This is a good way to avoid namespace pollution. Once executed, it cannot ever be executed again, since it wasn't actually saved anywhere.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With