Main Page

Be scope aware

Be scope aware
In JavaScript, scope is everything. A scope can be thought of as the space where certain variables exist.
The default (or global) scope is the
window
in JavaScript. Variables created in the window scope aren’t
destroyed until the Web page is unloaded from the browser. Each function you define is another scope
under that global scope. All variables created within the function exist only within the function scope
and are destroyed when execution leaves the function.
You can think of scopes in JavaScript as a hierarchical tree. When a variable is referenced, the JavaScript
interpreter looks to the most recent scope to see if it exists there. If not, it goes up to the next scope, and
the next, and so on, until it reaches the
window
scope. If the variable is not found in the
window
scope,
you receive an error during execution.
Every time the interpreter goes up to another scope in search of a variable, execution speed suffers.
Variables that are local to a scope lead to faster script execution when compared to global variables. The
less distance the interpreter has to travel up the tree, the faster your script runs. But what exactly does
this mean? Consider the following example:
var sMyFirstName = “Nicholas”;
function fn1() {
alert(sMyFirstName);
}
function fn2() {
var sMyLastName = “Zakas”;
fn1();
}
function fn3() {
var sMyMiddleInitial = “C”;
fn2();
}
fn3();
When
fn3()
is called on the last line, a scope tree is created (see Figure 19-1).
The importance of understanding scopes becomes evident in this example as you travel down the scope
tree. The function
fn3()
calls
fn2()
, which calls
fn1()
. The function
fn1()
then accesses the
window
-
level variable
sMyFirstName
, but in order to locate this variable, the interpreter has to look back up the
scope tree all the way to the window scope. This takes significant time. Finding ways to take advantage
of JavaScript scoping is vital in optimizing execution time. You can do a few easy things to help the
interpreter locate variables faster.
579
Deployment Issues
22_579088 ch19.qxd 3/28/05 11:43 AM Page 579


JavaScript EditorFree JavaScript Editor     Ajax Editor


©