↑
Main Page
with statement
The with statement
The
with
statement is used to set the scope of the code within a particular object. Its syntax is the
following:
with (
expression
)
statement
;
For example:
var sMessage = “hello world”;
with(sMessage) {
alert(toUpperCase()); //outputs “HELLO WORLD”
}
In this code, the
with
statement is used with a string, so when the
toUpperCase()
method is called, the
interpreter checks to see if this is a local function. If not, it checks the
sMessage
pseudo-object to see if
toUpperCase()
is a method for it, which it is. The alert then outputs
“HELLO WORLD”
because the inter-
preter finds the implementation of
toUpperCase()
on the
“hello world”
string.
The switch statement
The cousin of the
if
statement, the
switch
statement, allows a developer to provide a series of
cases
for
an expression. The syntax for the switch statement is:
switch (
expression
) {
case
value
:
statement
break
;
case
value
:
statement
break
;
case
value
:
statement
break
;
...
case
value
:
statement
break
;
default
:
statement
}
Each case says “if
expression
is equal to
value
, execute
statement
”. The
break
keyword causes code execu-
tion to jump out of the
switch
statement. Without the
break
keyword, code execution falls through the
original case into the following one.
The
default
keyword indicates what is to be done if the expression does not evaluate to one of the
cases (in effect, it is an
else
statement).
The
with
statement is a very slow segment of code, especially while the values of
properties are being set. Most of the time, it’s best to avoid using it if possible.
58
Chapter 2
05_579088 ch02.qxd 3/28/05 11:35 AM Page 58
Free JavaScript Editor
Ajax Editor
©
→ R7