1

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.

Community
  • 1
  • 1
Felice Pollano
  • 31,141
  • 8
  • 67
  • 108
  • 3
    The difference is discussed here: http://stackoverflow.com/questions/336859/javascript-var-functionname-function-vs-function-functionname/336868#336868 – kinakuta Oct 10 '12 at 19:07
  • I think this may be the third time today this has been asked. – I Hate Lazy Oct 10 '12 at 19:26

1 Answers1

4

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 foo and function foo statements in JavaScript get hoisted to the top of their closing scope (nearest function parent). This means that:

(function () { //closure for scope
  doStuff();
  var foo = bar;
}());

is actually:

(function () {
  var foo;
  doStuff();
  foo = bar;
}());

functions react similarly:

(function () {
  doStuff();
  function foo() {
    bar = baz;
  }
}());

is the same as:

(function () {
  function foo() {
    bar = baz;
  }
  doStuff();
}());

This distinction is important because a function declared in a variable isn't accessible until after it's been declared:

(function () {
  foo(); //this doesn't work and will result in an error
  var foo = function () {
    alert('works');
  };
}());

whereas a function is accessible as long as it's somewhere within scope:

(function () {
  foo(); //works!
  function foo() {
    alert('works!');
  }
}());
zzzzBov
  • 157,699
  • 47
  • 307
  • 349