Possible Duplicate:
JavaScript: var functionName = function() {} vs function functionName() {}
I would like to know if there is some hidden difference between the two following constructor function:
var Person = function(name){
this.say=function(){
console.log(name);
}
}
and this one:
function Person(name){
this.say=function(){
console.log(name);
}
}
suppose we are always going to write:
var x = new Person('xxxxx');
x.say();
It appear to be the same in order to me, but I’m really green in javascript and I would like to know if some form is wrong and if there is some best practices to follow.
There is no difference as far as constructors are concerned. All functions in JavaScript can be called as constructors (whether they throw errors or not is a different issue altogether).
The difference is between how the functions are declared.
The first declaration is as a variable that requires execution. The second declaration is as a function that is hoisted.
var fooandfunction foostatements in JavaScript get hoisted to the top of their closing scope (nearestfunctionparent). This means that:is actually:
functions react similarly:
is the same as:
This distinction is important because a function declared in a variable isn’t accessible until after it’s been declared:
whereas a function is accessible as long as it’s somewhere within scope: