What is the difference between these 2 syntactic function types

As the name says, what is the difference between

MyFunction = function() {

}

      

and

function MyFunction() {

}

      

Nothing

Duplicate: var functionName = function () {} vs function functionName () {}

+1


source to share


5 answers


The first form is actually a variable with an anonymous function assigned to it , the second is a declared function...



They are almost interchangeable, but they have some differences: it is more difficult for debuggers to work with anons (because they lack a name), and the JS engine can directly access the declared functions wherever they exist in the script, but anons can "access them before until they are assigned.

+1


source


I think you mean

var MyFunction = function() {
}

      

And in many cases, the difference is small.



The var syntax is sometimes useful when you are in some kind of packaging class and want to be sure of your namespace (like greasemonkey).

Also, I believe that constructor functions (with .prototype, etc.) do not work with var syntax.

0


source


here is one difference:

function Moose() {
   alert(arguments.callee.name); // "Moose"
}
var Cow = function() {
   alert(arguments.callee.name); // ""
}

      

0


source


function myFunction(){}

matches var myFunction = function myFunction(){}

. If you just execute MyFunction = function(){}

, it looks like MyFunction = function anonymous(){}

.

Variables and functions have different scopes, but a function can only be specified outside the function through the name of the variable that must be bound to the function.

function myFunction(){}

binds a variable myFunction

to a function that has the same name.

0


source


There is one subtle difference in Firefox when you declare a window event handler load

. Declaring the following in a script tag only works with Firefox:

function onload() {
    alert(42);
}

      

You have to do it like for IE, Opera, Safari or Chrome:

onload = function () {
    alert(42);
}

      

-1


source







All Articles