As the title says, whats the difference between
MyFunction = function() {
}
and
function MyFunction() {
}
Nothing?
As the title says, whats the difference between
MyFunction = function() {
}
and
function MyFunction() {
}
Nothing?
I think you mean
var MyFunction = 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.
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.
here is one difference:
function Moose() {
alert(arguments.callee.name); // "Moose"
}
var Cow = function() {
alert(arguments.callee.name); // ""
}
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);
}
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.