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.
<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.
Get Learning PHP, MySQL, and JavaScript now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.