Main Page

Use local variables

Figure 19-1
Use local variables
Always use the
var
statement to define variables inside functions. Whenever you used
var
, a local vari-
able is created within the current scope. If you begin using a variable without first defining it with
var
,
the variable is created at the
window
scope, meaning that every time you use that variable the interpreter
has to search back up the scope tree to find it. For example, don’t do this:
function sayFirstName() {
sMyFirstName = “Nicholas”;
alert(sMyFirstName);
}
In this function, the variable
sMyFirstName
is assigned a value without using
var
; this variable is cre-
ated at the
window
scope. You can prove this to yourself by defining another function that also uses this
variable:
function sayFirstName() {
sMyFirstName = “Nicholas”;
alert(sMyFirstName);
}
function sayFirstNameToo() {
alert(sMyFirstName);
}
sayFirstName();
sayFirstNameToo();
In this example, you see two alerts displaying
“Nicholas”
. This happens because the first function call,
sayFirstName()
, creates the variable
sMyFirstName
at the window scope, which means the second
MyMiddleInitial = "C"
MyFirstName = "Nicholas"
(window)
(window)
fn3()
fn3()
fn2()
fn2()
MyLastName = "Zakas"
fn1()
fn1()
580
Chapter 19
22_579088 ch19.qxd 3/28/05 11:43 AM Page 580


JavaScript EditorFree JavaScript Editor     Ajax Editor


©