A constructor function is a way to create a function that will constructor a type of object that contains methods and properties that are not unique properties and methods of the object itself, but are contained in the prototype object of it. If you have logged any about of time at all playing around with javaScipt chances are you might have all ready used the new keyword with a built in constructor such as the Date constructor for example.
In this post I will be touching base with some examples that make use of the new operator, and some related subjects to the use of the new operator and constructor functions that are what the new operator is often used with.
To use the new operator just type new and then the constructor function that there needs to be an instance of. If no parentheses are used then default values will be used for any arguments, otherwise use parentheses to give one or more arguments to the constructor function.
So Say I want to use the new keyword to create a new instance of Date, I can do so like this.
In this example the d variable is an instance of Date that was created using the new operator with the Date constructor function. Once I have my instance of Date I can use any of the prototype methods of the Date constructor such as Date.getDate. In addition to methods that are part of the Date constructor I can also make use of any additional prototype methods that may be in the prototype chain including the hasOneProperty methods that is part of the base Object prototype.
To create my own constructor function I just need to create a function and in the body of the constructor function or any prototype method I just use the this keyword as a way to refer to any property that is to be an OwnProperty of an instance of this constructor when created using the new operator.
If I where to to call this method without using the new operator the method would return the undefined value which is the default value that is return when a function is called in that manner without the use of the new keyword.
When using the new keyword with no arguments passed to the constructor this will still result in a new instance of the constructor, but with undefined values for all the arguments. So it is often a good idea to work out some kind of solution to have default values for arguments that are not given. When it comes to using the built in Date constructor it is possible to not give any arguments at all, and when doing so the default end up being the current local system time.
One way to go about doing this is to just test for the value of undefined using a conditional operator, and then set a default value in the event that the value is undefined, while just passing along the argument value that is given in any other case.
There are many more ways to go about doing this sort of thing that I might get around to here at some point when it comes to editing. However maybe getting to deep into this would be a little off topic.