Functions and Object Constructors
Functions in JavaScript are multipurpose. All functions in JavaScript are both objects in their own right and in most cases are also methods of a parent object.
The one instance where a function is not a method of a parent object is where it is being called to construct a brand new object. To do this you call the function using the new keyword, for example:
There is a convention used by some JavaScript programmers to always start the names of functions used that way with a capital letter and to always start all other function names with a lowercase letter. There is nothing in the language to enforce this and there are in fact built in functions/objects that do not follow that rule. Let's look at an example of where JavaScript itself doesn't follow that convention.
var today = new Date();
In this example we have called the built in date function and assigned the returned value to mydate and then created a date object called today. Both of these statements have called the same built in function but in different ways and so the first call returns a value from a regular function call and the second creates a new object. The code built into the language itself is able to distinguish between the two different ways that the function can be called within the function itself so as to provide the appropriate processing for each of the two similar appearing but very different calls.
We can in fact apply this same test within our own JavaScript functions. With the appropriate test incorporatefd into our function we can either produce an error message if the function is called the wrong way or provide two different lots of code so as to allow the function to be used both ways the way that the built in Date function can be.
if (this === window || 'myFunction' in this) {
// normal function processing goes here
} else {
// new object create processing goes here
}
}
The way that this code works is very simple. The if statement tests if the function is a method of the window object (as it would be if you use a regular function definition and call it as a regular function) or if it is a method of an object. The this keyword always points to the object to which the method belongs if it is called normally.
When a function is called using new the this keyword doesn't point to the object that the function is a part of, it points to the new object that is being created and until you actually start assigning properties and methods to it the new object will not contain anything.
By actually testing how our function was called we can ensure that our functions are always called the way that we intend without relying on the convention of using upper or lower case letters on the front of the name to distinguish the intended use.

