The with StatementYou 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:
The with statement has been around a long time, as you see in Table 3.5. Table 3.5. The with Statement
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> |