tags:

views:

112

answers:

2

Possible Duplicate:
Explain JavaScript's encapsulated anonymous function syntax

I have just read a javascript book but I have seen this code:

1(function() {

          // code

})();

what is this ? is a special function ?

+1  A: 

It looks like the intent was to declare the function inline/anonymous and immediately execute it.

James
+1  A: 

As written, it has a syntax error.

I'm guessing it was more like:

(function() {
          // code
})();

or

(function() {
          // code
    }
)();

Break it down:

(FOO)() // calls FOO with no arguments.

And

function() { //creates a function that takes no arguments.
      // code
}

Hence together it would create a function that takes no arguments, and then call it. I can't see why you would apart from just showing that you can.

Jon Hanna
You do so in JavaScript to create a protected scope. `var` s defined in that block will not be accessible in the outer scope.
gnarf
@gnarf. Yep, that's it!
Jon Hanna