¿Qué significa esta sintaxis? (función () {// código}) () [duplicado]

Posible duplicado:
¿Qué significan los paréntesis que rodean una declaración de clase / función / objeto de JavaScript?
¿Qué significa esta sintaxis de JavaScript?
What does this “(function(){});”, a function inside brackets, mean in javascript?

In the below code the anonymous function is being executed.

var a= 1;
var b =2;           
(function() {  
    var b = 3;  
    a += b;  
})();  
document.write(a + " "+ b);

1) What does putting parenthesis around the function definition do?

2) What does putting () after the closing parenthesis do?

preguntado el 31 de enero de 12 a las 08:01

Lea esto: stackoverflow.com/questions/593509/… hope this helps :) -

4 Respuestas

Poniendo el () alrededor del function() { ... } makes it an expression vs. a statement. Because it's an expression which produces a function value the () at the end invoke the produced function.

Consider the alternatives

function () { 
  var b = 3;
  a += b;
}();

This produces a syntax error as the () are essentially trying to invoke a statement.

(function () {
  var b = 3;
  a += b;
});

Esto produce un function object which is never invoked.

Respondido el 31 de enero de 12 a las 12:01

Well you say it in the first line, the code creates an anonymous function then executes it with no arguments (the trailing parenthesis)

Respondido el 31 de enero de 12 a las 12:01

Don't know why yours was given a down vote without any comments as your answer looks valid in my non-expert Javascript opinion. - CadentOrange

It a function executes it self,if you want to create an scope(or define local varible),because javascript has no block scope,a function is needed.

Respondido el 31 de enero de 12 a las 12:01

ok, Your first question answer is just covering the hole function.without it function will executed and the second one is an anonymous function with no arguments.

Respondido el 31 de enero de 12 a las 12:01

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.