The difference in the constructors: var X = function () {}, var X = function X () {} and function X () {}

Now I'm debugging someones else code, and I'm just confused when it defines a constructor in these two modes. Is there anything special between the two?

//constructor 1 var MyObject = function(){ }; //constructor 2 var MyObject = function MyObject(){ }; 

Also, which means just creating a function that way.

 function MyObject(){}; 

I just look at some use cases for each.

+7
javascript
source share
2 answers

Various options:

1) The function is not named, so you will not get the name of the function in MyObject.toString()

 var MyObject = function(){}; 

2) The function is named, so you get the function name in MyObject.toString() , but this is still not recommended.

 var MyObject = function MyObject (){}; 

Effectively, there is no practical difference between (1) and (2)

3) Function declaration instead of function expression ( See related discussion )

 function MyObject() {} 

This differs from the previous parameters in that it is in the area before the actual declaration, so the following code works fine:

 MyObject(); function MyObject() {} 

But if you try this:

 MyObject(); var MyObject = function(){}; 

You will receive an error message.

I usually just stick to option 1, as it seems the most logical

+2
source share

The only difference between them is the latter, you can refer to the function internally by the name of the function (although in your case they have the same name). In some old IEs, they leaked this name into the surrounding area.

It is also useful to name it for things like checking the call stack - a named function is the name that will be used (at least in the Chrome inspector).

0
source share

All Articles