-1

Possible Duplicate:
What is the purpose of a self executing function in javascript?

Please, can someone explain to me what does that mean in JS:

var obj = (function(){ 
   // code
})()

Thanks

Community
  • 1
  • 1
WHITECOLOR
  • 24,996
  • 37
  • 121
  • 181

2 Answers2

5

It's called an immediately instantiated function. It runs the function, and the returned value is assigned to obj. You can create a scope or class with it, in which you can use closures to keep certain variables private within that scope. See John Resigs page on that subject.

So, if the function looks like this:

var obj = (function(n){
  return 2+n;
})(3);

The value of obj would be 5.

KooiInc
  • 119,216
  • 31
  • 141
  • 177
5

It is an anonymous function that is immediately executed. It's return value is assigned to obj. For example:

var obj = (function () {
    return 10;
}()); //Notice that calling parentheses can go inside or outside the others

console.log(obj); //10

They are often used to introduce a new scope so you don't clutter the scope the code is executing in:

var obj = (function () {
    var something = 10; //Not available outside this anonymous function
    return something;
}());

console.log(obj); //10

Note that since this is a function expression, and not a function declaration, it should have a semi-colon after the closing curly brace.

James Allardice
  • 164,175
  • 21
  • 332
  • 312