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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With