|Written by Ian Elliot|
|Wednesday, 21 September 2011|
Page 1 of 3
The key idea is that we are going to create a special type of Date object that stores the time interval as a number of milliseconds.
The object augmentation pattern:
Let's use the augmentation pattern to create a TimeInterval object from the Date object.
We first need a new factory function for the TimeInterval object:
All this has to do is create and return a Date object:
var obj=new Date();
That is the new factory function is:
Now all we have to do is add the new properties and methods we require for the TimeInterval object. Notice that this is an object factory, rather than a constructor, and you don't have to use the new keyword with it. If you do use the new keyword it doesn't make any difference - it just isn't necessary as the function creates its own object to return rather than relying on the default object.
The overloaded factory function
The first thing that we would like to do is create a factory function that is flexible in the way itinitializes the new object. That is, we would like to be able to write:
The key to creating a flexible factory function is to work with the arguments array directly to work out what parameters have been specified.
In this case we can do the job with a few if statements:
So depending on the number of arguments we set the variables d, h, m, s and mill accordingly. You might wonder why we use valueOf? The simple reason is that this allows the user to specify any object that has a numerical value. For example without valueOf the statement:
var t=TimeInterval(new Date());
wouldn't be allowed as you are expecting an integer number of milliseconds. However in this case the Date().valueOf() returns an integer value which is the number of milliseconds from the fixed date.
At the end of all of the if statements we have a specification of the time interval in terms of d,h,m,s and mill and we need to convert this into milliseconds and use it to create a Date object:
Now the object factory returns a Date object initialized to the correct time interval in milliseconds.
|Last Updated ( Tuesday, 10 September 2013 )|