-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

0

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.