Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference in constructors: var X = function (){}, var X = function X(){}, and function X(){} [duplicate]

Tags:

javascript

I am debugging someones else code now and I am just confused when he defines constructor in these two modes. Is there anything special between the two?

//constructor 1
var MyObject = function(){

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

};

Also, whats the effect of just creating a function just like this.

function MyObject(){};

I am just looking at certain use cases for each.

like image 673
Mark Estrada Avatar asked Aug 15 '14 07:08

Mark Estrada


1 Answers

The different options:

1) Function is not named, so you don't get a function name in MyObject.toString()

var MyObject = function(){};

2) Function is named, so you get a function name in MyObject.toString(), but this is deprecated anyway.

var MyObject = function MyObject (){};

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

3) Function declaration instead of function expression (See discussion on topic)

function MyObject() {}

This is different from the previous options in that it is in scope before the actual declaration, so the following code works fine:

MyObject();
function MyObject() {}

But, if you try this:

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

You get an error.

I generally just stick to option 1, since it seems to be the most logical

like image 159
neelsg Avatar answered Oct 04 '22 05:10

neelsg