Skip to Navigation or Skip to Content

Steve Fenton
Author of The Reason Your Website Sucks

JavaScript Constructors Are Just Functions

You Are Here: Home » Blog » JavaScript Constructors Are Just Functions

Feeds

RSS Feed

<< June | July | August >>

Wednesday, 28th July 2010

I was recently asked a question about JavaScript constructors, which highlighted to me that this statement isn't as well known as it ought to be:

JavaScript Constructors Are Just Functions

There is absolutely no difference between the two, except how you use them. It's a bit like a pencil. In my hands it is a writing and drawing instrument, but to some people I know it's a device for removing ear-wax.

So here are some examples to back up the statement. Firstly, a function...

  1.  
  2. function AddTwoNumbers(first, second) {
  3. return first + second;
  4. }
  5. // Use it as a function
  6. var a = AddTwoNumbers(3, 5);
  7. // Use it as a constructor
  8. var b = new AddTwoNumbers(3, 5);
  9.  

In this example, a will be equal to 8, but b will be a new object instance of "AddTwoNumbers".

Obviously this is entirely useless behaviour. You should never write a dual function/constructor as it is no use to anyone, but the important thing to take away from this example is that a function is only ever a constructor when you call it with the "new" keyword.