Java Reference
In-Depth Information
This is demonstrated in the following code:
var nowDate = new Date();
nowDate.setHours(9);
nowDate.setMinutes(57);
alert(nowDate);
nowDate.setMinutes(64);
alert(nowDate);
First you declare the nowDate variable and assign it to a new Date object, which will contain the cur-
rent date and time. In the following two lines, you set the hours to 9 and the minutes to 57. You show
the date and time using an alert box, which should show a time of 9:57. The minutes are then set to
64 and again an alert box is used to show the date and time to the user. Now the minutes have rolled
over the hour so the time shown should be 10:04.
If the hours were set to 23 instead of 9, setting the minutes to 64 would not just move the time to
another hour but also cause the day to change to the next date.
Creating New Types of Objects (Reference Types)
This section's focus is on some advanced stuff. It's not essential stuff, so you may want to move on and
come back to it later.
You've seen that JavaScript provides a number of objects built into the language and ready for us to
use. It's a bit like a house that's built already and you can just move on in. However, what if you want to
create your own house, to design it for your own specifi c needs? In that case you'll use an architect to
create technical drawings and plans that provide the template for the new house — the builders use the
plans to tell them how to create the house.
So what does any of this have to do with JavaScript and objects? Well, JavaScript enables you to be an
architect and create the templates for your own objects to your own specifi cation, to fi t your specifi c
needs. Let's say, for example, you were creating a cinema booking system. JavaScript doesn't come with
any built-in cinema booking objects, so you'd have to design your own. What you need to do is cre-
ate objects modeled around the real world. So for a simple cinema booking system, you might have an
object representing customers' booking details and an object for the cinema where the bookings have
been made. As well as being able to store information, you can create your own methods for an object.
So for a booking system, you might want an “add new booking” method or a method that gets the
details of all the bookings currently made.
Where you have no need to store data but simply want functionality, such as the fix() function you
saw before, it's generally easier just to have a code library rather than to create a special object.
Just as a builder of a house needs an architect's plans to know what to build and how it should be laid
out, you need to provide blueprints telling JavaScript how your object should look. For example, you
need to defi ne its methods and provide the code for those methods. The key to this is JavaScript's sup-
port for the defi nition of reference types . Reference types are essentially templates for an object, as the
Search WWH ::




Custom Search