Hay algunas cosas que puede hacer con una expresión de función que no puede con una declaración.
que podría ser invocada inmediatamente, y el valor de retorno se almacena en la variable
si no estás en el espacio de nombres global, que podría excluir la palabra clave var
para crear un mundial
EDIT:
Aquí hay un ejemplo de una invocación inmediata. Devuelve una función a la variable myFunctionName
que tiene acceso a las variables y al parámetro delimitado en la función invocada inmediatamente.
var myFunctionName = function(v) {
// do something with "v" and some scoped variables
// return a function that has access to the scoped variables
return function() {
// this function does something with the scoped variables
};
}('someVal');
// now this function is the only one that has access
// to the variables that were scoped in the outer expression.
myFunctionName();
Aquí hay un ejemplo donde una función mantiene un valor numérico. Puede llamar repetidamente a la función y darle un número para agregar al recuento. Siempre hará referencia al valor actual, por lo que cada llamada es acumulativa.
Ejemplo:http://jsfiddle.net/5uuLa/1/
var counter = function(value) {
return function(addValue) {
value += ~~addValue;
return value;
};
}(10); // initialize with a value
// each call builds on the result of the previous
console.log(counter(2)); // 12
console.log(counter(5)); // 17
console.log(counter(3)); // 20
console.log(counter(7)); // 27
console.log(counter(1)); // 28
leer el artículo de la primera respuesta - http://stackoverflow.com/questions/1013385/what-is-the-difference-between- a-function-expression-vs-declaration-in-javascript Enlace directo al artículo - http://kangax.github.com/nfe/ – leebriggs