0

I have studied Javascript for a litte while now but I can't seem how to spot the difference if a statement is a function or constructor. This is the code for a Constructor:

function Book (pages, author) {
this.pages = pages;
this.author = author;
}

And this is a simple function:

var cars = function(printCar){
console.log(blabla);
};

However I have seen in serveral tutorials(i.e CodeCademy) that they are using the constructor syntax for making functions aswell. How is this possible?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Essej
  • 892
  • 6
  • 18
  • 33
  • The difference you mentioned is actually between function expression and function statement. – raina77ow Sep 09 '14 at 17:05
  • There's a mistake in your "simple function" example; I'm not sure if you meant to say var something = function(printCar) or if you meant function something(printCar). – Paul Sep 09 '14 at 17:07
  • Constructors start with a captial letter, unless a fool coded it. – dandavis Sep 09 '14 at 17:15

1 Answers1

3

There is no syntactic difference. All (user-defined) functions can be called both as a function/method or as a constructor. Whether it's a function declaration or a expression doesn't matter:

var Book = function() { … };
function Book() { … }
var example = function() { … };
function example() { … };

However, naming functions is always encouraged, and there's no reason to write var example = function() { … } when you can use a declaration. There are some cases though where an expression (which is typically anonymous) is required, or where declarations are invalid.

What they are and what they do is entirely determined by their body code. Constructors typically set properties on this, however methods will do that as well. Constructors usually have no return statement, as the new operator implicitly returns the created instance.

A convention for distinguishing them is that constructor functions have a capitalized name.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Okay! Then I understand, thanks. Is it beter to use the "function syntax" or the "Constructor syntax" when creating functions? Or that doesn't matter? – Essej Sep 09 '14 at 17:08
  • It doesn't matter, but as he said it's about convention. So from that perspective, it probably is slightly more maintainable to write functions using function syntax and constructors using constructor syntax. So the next guy maintaining your code has a bit more clarity on your intent. – Paul Sep 09 '14 at 17:10
  • @Baxtex: there is no "function" or "constructor" syntax. You probably mean the distinction in "function expressions" and "function declarations", see the link I've posted. Declarations are better if you can use them. – Bergi Sep 09 '14 at 17:14