Skip to Navigation or
Skip to Content

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...

function AddTwoNumbers(first, second) {
    return first + second;
}
// Use it as a function
var a = AddTwoNumbers(3, 5);
// Use it as a constructor
var b = new AddTwoNumbers(3, 5);

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.

 

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

 

I use a cookie on this website. This cookie doesn't contain or relate to any personal information and it isn't shared with any other website, it just ensures that I don't count you more than once in my website statistics. The Privacy and Electronic Communications Regulations require me to ask your permission to use this cookie, so please indicate below that you are happy for me to do this - I will remember your selection with a cookie, so if you accept I won't ask again...