What is the difference between these two?
collapse: function(fold)
{
...
...
}
and
function collapse(fold)
{
...
...
}
The first one outside of the context of an object literal is a syntax error.
However, I believe you are asking about the difference between a function expression and a function declaration.
Your first one is a function expression. You assign an anonymous function to a variable. Its variable definition is hoisted to the top of its scope, but not the assignment of the function.
The second is the function declaration. Its entire body is hoisted to the top of the scope.
In general, a function expression is often used as it is more expressive. You can give it a name if you need to call it recursively (or for better detailed stack traces), but remember IE leaks this name to the outer scope.
Further Reading.
The first code is only valid to produce a property inside an object definition, like so:
var obj = {
collapse: function(fold)
{
...
...
}
};
That function would be called by calling obj.collapse(fold);
The second function is simply called using collapse(fold);
As for the difference between var name = function() { ... } and function name() { ... } see: var functionName = function() {} vs function functionName() {}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With