Possible Duplicate:
JavaScript scope and closure
I am not very familiar with the Javascript syntax bellow. Can anyone shade light about the sense of this block? For what purpose?
(function foo() { alert('bar'); })();
Thanks in advance.
Possible Duplicate:
JavaScript scope and closure
I am not very familiar with the Javascript syntax bellow. Can anyone shade light about the sense of this block? For what purpose?
(function foo() { alert('bar'); })();
Thanks in advance.
That looks like bad practice to me (naming a closure function), because it can cause browser inconsistencies.
Take the following code for example
(function foo() {
alert('bar');
})();
foo();
In Internet explorer you will get 2 alerts, because it actually creates the function as a global function called foo
.
In Chrome, it will only alert once, and foo
isn't declared globally, so you get a javascript error foo is not defined
Normally you wouldn't give a name to a closure function
(function() { // notice you don't see foo anymore
alert('bar');
})();
The purpose is to bring the scope of what you are working on out of global scope. This helps to encapsulate your objects and keep them from polluting the global pool. Any variables you declare globally to the containing function foo() will not be available except to functions declared within the function foo()
var GLOBALVAR //this is available to the global document scope
(function foo() {
var FOOVAR //only available within this function
function bar(){
FOOVAR = GLOBALVAR //this will work
}
alert('bar');
})();
FOOVAR = GLOBALVAR //This will not because FOOVAR is out of scope
Javascript allows you to declare functions on the fly - they're called closures - and is done in your example between the first sets of parenthesis. When you introduce the second set of parenthesis, you're calling that function you just defined. The distinction to note is the difference between function declaration/definition and application of that function.
var tokenizer = (function(){ var id = 0; return function() { return id++; }; })();
tokenizer(); // 0
tokenizer(); // 1
tokenizer(); // 2
alert(id); // undefined