Sometimes, you have a lot of operations to perform with the properties
and methods of a single object. You might be doing trigonometry and need
to make reference to many properties of the Math object, or be
implementing a browser-identification script and need to work with the
Navigator object a lot. More interestingly, you could be working with
custom objects and need to populate their properties at creation time.
The with statement can make your job easier. The following code will
work, but it's long and ugly:
sineOfTheTimes = Math.sin(Math.PI/2);
cosineMyMortgage = Math.cos(Math.E);
danRatherIsATanGent = Math.tan(Math.PI);
By using with, we make life easier:
with(Math) {
sineOfTheTimes = sin(PI/2);
cosineMyMortgage = cos(E);
danRatherIsATanGent = tan(PI);
}
Neater!
By the way: You'll recall that, a few weeks ago, we talked about using
the document.lastModified property to tag Web pages with the date and
time of their last change. The property itself is a Date object, which
means you can use various methods to pick out parts of the date and time
(the month and the year, for example) in order to reformat the date more
attractively. An excellent application that uses the
document.lastModified property, complete with a utility that formats the
date nicely and gets around turm-of-the-millenium problems, is here:
http://www.chami.com/tips/internet/041198I.html_