That is an outstanding explanation, thanks!

Michael Geary wrote:
From: Leandro Vieira Pinho
(function(){
...
})();

I would like to know, what´s the name of that sintax.

From: Josh Nathanson
Is that a closure?

Not exactly. One common use of the "anonymous function called in place" is
to create a closure, but this itself isn't a closure.

For example:

   (function() {
      var message = 'hello';
      function test() { alert(message); }
      test();
   })();

   test();  // fails

There's no closure here, because there are no references outside the
function to any of the function's local variables or local functions.
However, there is a local scope, so the call to test() outside the anonymous
function will fail (as expected).

   var test1;

   (function() {
      var message = 'hello';
      function test() { alert(message); }
      test();
      test1 = test;
   })();

   test1();  // succeeds
   test(); // fails

Almost the same thing, but the "test1 = test;" statement creates a reference
to the test function *outside* the anonymous function. Now we have a
closure, where variables local to the function are preserved for later use
outside the function.

Basically, every function call creates a local scope. If the function
creates any references to its local variables or functions that are outside
the function, then a closure is created to save those variables. The closure
remains in existence as long as any of those references are kept.

This is true for named functions as well as anonymous functions - there's no
difference between the two.

People do often refer to a local scope as a closure, but it's not really
correct - a closure refers specifically to the situation where local
variables and local functions outlive the function call in which they were
created.

-Mike


Reply via email to