The with Statement


The with Statement

You should know about another statement when working with loops : the with statement. This statement is not a loop by itself, but it's not all that different. It enables you to specify a default object with which the statements in the body of the with statement can work. If you make document the default object, for example, you can use write alone without having to specify document.write . Here is the syntax of this statement:

 with (  object  ){  statements  } 

The following parts comprise this statement:

  • object . Specifies the default object to use for the statements. The parentheses around object are required.

  • statements . Any set of statements.

The with statement has been around a long time, as you see in Table 3.5.

Table 3.5. The with Statement

Statement

NS2

NS3

NS4

NS6

IE3a

IE3b

IE4

IE5

IE5.5

IE6

with

x

x

x

x

x

x

x

x

x

x

Here's an example, using the JavaScript Math object, which we'll see more about in Chapter 19, "The Math , Number , Boolean , and Array Objects." This object has many useful built-in methods , such as cos and sqrt to take cosines and square roots respectively, and properties, such as PI , which holds the value of pi. If you're using the Math object a lot, it's easier to use a with statement than to always have to qualify every method and property name with the Math object (that is, Math.PI , Math.cos , and so on), like this:

(Listing 03-06.html on the web site)
 <HTML>      <HEAD>          <TITLE>              Using the with Statement          </TITLE>      </HEAD>      <BODY>          <H1>Using the with Statement</H1>          <SCRIPT LANGUAGE="JavaScript">              <!--  with(Math){   document.write("cos(pi) = " + cos(PI) + "<BR>")   document.write("sqrt(4) = " + sqrt(4) + "<BR>")   }  // -->          </SCRIPT>      </BODY>  </HTML> 


Inside Javascript
Inside JavaScript
ISBN: 0735712859
EAN: 2147483647
Year: 2005
Pages: 492
Authors: Steve Holzner

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net