Like the ternary conditional operator, the with statement is a shortcut. Instead of having to list all of the properties of an object by repeating the basic object, you can state the bulk of the object in a with statement and then the properties within the context of the with statement. For example, take a typical form object. First you must state the object as follows:
document.formName...
Then you follow with the element names and values:
…elementName.value
Thus, your statement would be
document.formName,elementName.value
A typical form could include several different elements, such a first name, last name, address, city, state, ZIP code, Social Security number, and all other kinds of property details. Using the with statement, you can specify the object name once and then follow it with all of the properties and their values in this format:
with (object) {
statements with properties only
}
The statements are typically property values. In the following simple example, the script uses a single with statement and then places the property values of the object in the statements within the with context:
<html>
<head>
<title>with</title>
<script language="JavaScript">
function showEm(){
with (document.customer) {
var alpha=fname.value;
var beta=lname.value;
var gamma=address.value;
var delta=city.value;
var epsilon=state.value;
}
var fullName=alpha + " " + beta + "\n";
var livesHere=gamma + "\n" + delta + ", " + epsilon;
alert(fullName + livesHere);
}
</script>
</head>
<body bgColor="cornsilk">
<form name="customer">
<input type=text name="fname"> First Name:
<input type=text name="lname"> Last Name:
<br>
<input type=text name="address"> Address:
<br>
<input type=text name="city"> City:
<input type=text name="state" size=2> State:
<p>
<input type=button value="Click Here" onClick="showEm()">
</body>
</html>
When and where to best use the with statement depends on the application, but, as can be seen from the example, it helps to clean up and simplify references to multiple properties in an object.
Our website is not responsible for the information contained by this article. Webworldarticles.com is a free articles resource thus practically any visitor can submit an article. However if you notice any copyrighted material, please contact us and we will remove the article(s) in discussion right away.
This article was sent to us by:
George Freedrich at
11042008
1. Types of operators in JavaScript
All articles in this directory are property of their respective authors. Additionally, read our Privacy Policy
© 2010 WebWorldarticles.com - All Rights Reserved. Partners: Gunblade Saga