Java Reference
In-Depth Information
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
current 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 Your oWn Custom objeCts
We've spent a lot of time discussing objects built into JavaScript, but JavaScript's real power comes
from the fact that you can create your own objects to represent complex data. For example, imagine
that you need to represent an individual person in your code. You could simply use two variables for
an individual person's first name and last name, like this:
var firstName = "John";
var lastName = "Doe";
But what if you needed to represent multiple people? Creating two variables for every person
would get unwieldy very quickly, and keeping track of every variable for every person would cause
headaches for even the best programmers in the world. Instead, you could create an object to
represent each individual person. Each of these objects would contain the necessary information
that makes one person unique from other (such as a person's first and last names).
To create an object in JavaScript, simply use the new operator in conjunction with the Object
constructor, like this:
var johnDoe = new Object();
But like arrays, JavaScript provides a literal syntax to signify an object: a pair of curly braces ( {} ). So
you can rewrite the previous code like this:
var johnDoe = {};
Today's JavaScript developers favor this literal syntax instead of calling the Object constructor.
Once you have an object, you can begin to populate it with properties. It is similar to creating a
variable, except you do not use the var keyword. Simply use the name of the object, followed by a
dot, then the name of the property, and assign it a value. For example:
johnDoe.firstName = "John";
johnDoe.lastName = "Doe";
These two lines of code create the firstName and lastName properties on the johnDoe object
and assign their respective values. JavaScript does not check if these properties exist before they're
 
Search WWH ::




Custom Search