↑
Main Page
Avoid the with statement
function,
sayFirstNameToo()
, can also access it. Suppose you now change this example to use
var
,
like this:
function sayFirstName() {
var sMyFirstName = “Nicholas”;
alert(sMyFirstName);
}
function sayFirstNameToo() {
alert(sMyFirstName);
}
sayFirstName();
sayFirstNameToo();
When you try to run this code, you get an error after the first alert is displayed because the second func-
tion has no knowledge of a variable named
sMyFirstName
. The variable was created within the
sayFirstName()
scope and was destroyed when the function finished executing.
Using local variables leads to faster execution because the interpreter doesn’t have to leave the local
scope in search of a variable. Local variables are also much more efficient because they are removed
from memory long before the Web page is unloaded.
Avoid the with statement
You probably understand at this point that the fewer scopes you have, the better off you are. This is why
it’s important to avoid the
with
statement whenever possible.
As a quick refresher, the
with
statement enables you to access properties of objects as if they were vari-
ables, so instead of doing this:
alert(document.title);
alert(document.body.tagName);
alert(document.location);
You can do this:
with (document) {
alert(title);
alert(body.tagName);
alert(location);
}
This saves bytes by eliminating the need to type
document
for each of the three lines contained in the
with
statement. But the
with
statement comes with a price: It is another scope. When you use the
with
statement, you are forcing the interpreter to not only look up the scope tree for local variables, but you
are also forcing it to test each variable against the object specified to see if it’s a property. After all, you
could have a variable named
title
or
location
defined within the function as well.
Your best bet is to avoid using the
with
statement. The number of bytes saved doesn’t outweigh the per-
formance loss because of an added scope.
581
Deployment Issues
22_579088 ch19.qxd 3/28/05 11:43 AM Page 581
Free JavaScript Editor
Ajax Editor
©
→