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 14-10, in which the document.write function never references the
variable string by name.
<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.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access