1

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.

Community
  • 1
  • 1
Fabien
  • 787
  • 1
  • 6
  • 11
  • and of http://stackoverflow.com/questions/2897987/why-would-one-write-global-code-inside-a-function-definition-call-pair – nico Jun 09 '10 at 16:47
  • and another http://stackoverflow.com/questions/592396/what-is-the-purpose-of-a-self-executing-function-in-javascript – Anurag Jun 09 '10 at 16:49
  • His question is different than those, since he has a name on his closure function, creating a completely different set of issues (Though, he may or may not have meant to) – Gordon Tucker Jun 09 '10 at 16:54

4 Answers4

2

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');
})();
Gordon Tucker
  • 6,653
  • 3
  • 27
  • 41
1

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
Jonathan Park
  • 775
  • 5
  • 12
0

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.

sholsapp
  • 15,542
  • 10
  • 50
  • 67
0

var tokenizer = (function(){ var id = 0; return function() { return id++; }; })();

tokenizer(); // 0
tokenizer(); // 1
tokenizer(); // 2
alert(id); // undefined
bernedef
  • 699
  • 2
  • 12
  • 22