O'Reilly logo

Learning PHP, MySQL, and JavaScript by Robin Nixon

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

The with Statement

The with statement is not one that you’ve seen in earlier chapters on PHP, because it’s exclusive to JavaScript. With it (if you see what I mean), you can simplify some types of JavaScript statements by reducing many references to an object to just one reference. References to properties and methods within the with block are assumed to apply to that object.

For example, take the code in Example 15-10, in which the document.write function never references the variable string by name.

Example 15-10. Using the with statement
<script>
string = "The quick brown fox jumps over the lazy dog"

with (string)
{
    document.write("The string is " + length + " characters<br />")
    document.write("In upper case it's: " + toUpperCase())
}
</script>

Even though string is never directly referenced by document.write, this code still manages to output the following:

The string is 43 characters
In upper case it's: THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG

This is how the code works: the JavaScript interpreter recognizes that the length property and toUpperCase() method have to be applied to some object. Because they stand alone, the interpreter assumes they apply to the string object that you specified in the with statement.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required