What Is The Difference Between These 2 Function Syntax Types
Solution 1:
The first form is actually a variable with an anonymous function assigned to it, the second is a declared function.
They're almost interchangeable, but have some differences: debuggers have a harder time with anons (because they lack a name) and the JS engine can directly access declared functions wherever they exist in the script, but anons can't be accessed until they have been assigned.
Solution 2:
I think you mean
varMyFunction = function() {
}
And in many cases, there is little difference.
The var syntax is sometimes useful when you are inside some sort of wrapping class and want to be sure of your namespace (like in greasemonkey).
Also, I believe the function-are-constructors stuff (with .prototype, etc) do not work with the var syntax.
Solution 3:
here is one difference:
functionMoose() {
alert(arguments.callee.name); // "Moose"
}
varCow = function() {
alert(arguments.callee.name); // ""
}
Solution 4:
function myFunction(){}
is the same as var myFunction = function myFunction(){}
. If you just do MyFunction = function(){}
, it's like MyFunction = function anonymous(){}
.
The variables and functions have different scopes but the function can only be referenced outside the function via the variable name, which needs to be bound to the function.
function myFunction(){}
binds the myFunction
variable to a function that just happens to have the same name.
Solution 5:
There's one subtle difference on Firefox, when you're declaring a window load
event handler. Declaring the following in a script tag only works on Firefox:
function onload() {
alert(42);
}
You have to do it like this for IE, Opera, Safari or Chrome:
onload = function () {
alert(42);
}
Post a Comment for "What Is The Difference Between These 2 Function Syntax Types"