Tải bản đầy đủ (.pdf) (11 trang)

Variables

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (139.77 KB, 11 trang )

Chapter 4. Variables
A variable is a name associated wit
the value. Variables allow you to sto
h a value; we say that the variable stores or contains
re and manipulate data in your programs. For
riable, sum:
3;
ut
e of
example, the following line of JavaScript assigns the value 2 to a variable named i:
i = 2;
And the following line adds 3 to i and assigns the result to a new va
var sum = i +
These two lines of code demonstrate just about everything you need to know abo
variables. However, to fully understand how variables work in JavaScript, you need to
master a few more concepts. Unfortunately, these concepts require more than a coupl
lines of code to explain! The rest of this chapter explains the typing, declaration, scope,
contents, and resolution of variables. It also explores garbage collection and the
variable/property duality.
[1]
[1]
These are tricky concepts, and a complete understanding of this chapter requires an understanding of concepts introduced in later chapters of
the book. If you are relatively new to programming, you may want to read only the first two sections of this chapter and then move on to
Chapter 5, Chapter 6, and Chapter 7 before returning to finish up the remainder of this chapter.
4.1 Variable Typing
An important difference between JavaScript and languages such as Java and C is that
JavaScript is untyped. This means, in part, that a JavaScript variable can hold a value of
hich can hold only the one particular type of
is perfectly legal in JavaScript to assign a
va, or any other strongly typed language, code like this is illegal.
A feature related to JavaScript's lack of typing is that the language conveniently and


f you attempt to
append a number to a string, for example, JavaScript automatically converts the number
ing string so that it can be appended. We'll see more about data type
onversion in
Chapter 11
any data type, unlike a Java or C variable, w
data for which it is declared. For example, it
number to a variable and then later assign a string to that variable:
i = 10;
i = "ten";
In C, C++, Ja
automatically converts values from one type to another, as necessary. I
to the correspond
c .
tage of strongly
typed languages such as C++ and Java is that they enforce rigorous programming
JavaScript is obviously a simpler language for being untyped. The advan
practices, which makes it easier to write, maintain, and reuse long, complex programs.
are shorter scripts, this rigor is not necessary and we
enefit from the simpler syntax.
Since many JavaScript programs
b
4.2 Variable Declaration
Before you use a variable in a JavaScript program, you must declare it.
[2]
Variable
declared with the
s are
declare it implicitly for you.
var i = 0, j = 0, k = 0;

is
var keyword, like this:
[2]
If you don't declare a variable explicitly, JavaScript will
var i;
var sum;
You can also declare multiple variables with the same var keyword:
var i, sum;
And you can combine variable declaration with variable initialization:
var message = "hello";
If you don't specify an initial value for a variable with the var statement, the variable
declared, but its initial value is undefined until your code stores a value into it.
Note that the var statement can also appear as part of the for and for/in loops
(introduced in Chapter 6), allowing you to succinctly declare the loop variable as part
the loop syntax itself. For example:
of
for(var i = 0; i < 10; i++) document.write(i, "<br>");
i++,j--) document.write(i*j, "<br>");
te(i, "<br>");
e
for(var i = 0, j=10; i < 10;
for(var i in o) document.wri
Variables declared with var are permanent: attempting to delete them with the delet
operator causes an error. (The delete operator is introduced in Chapter 5.)
4.2.1 Repeated and Omitted Declarations
It is legal and harmless to declare a variable more than once with the var statement. If t
repeated declaration has an initializer, it acts as if it were simply an assignment statement
he
.
If you attempt to read the value of an undeclared variable, JavaScript will generate an

best to use var for all
ariables, whether global or local. (The distinction between local and global variables is
ble Scope
l
defined everywhere in your JavaScript code. On the
e
nt
riable
e same
r example, the
ar scope = "global"; // Declare a global variable
function checkscope( ) {
checkscope( ); // Prints "local"
ou can get away with not using the var statement when you write code in the
global scope, you must always use
var to declare local variables. Consider what happens
le, even
obal
e(scope); // Uses the global variable
cal"; // This implicitly declares a new
(myscope); // Uses the new global variable
checkscope( ); // Prints "locallocal"
document.write(scope); // This prints "local"
document.write(myscope); // This prints "local"
error. If you assign a value to a variable that you have not declared with var, JavaScript
will implicitly declare that variable for you. Note, however, that implicitly declared
variables are always created as global variables, even if they are used within the body of
a function. To prevent the creation of a global variable (or the use of an existing global
variable) when you meant to create a local variable for use within a single function, you
ust always use the var statement within function bodies. It'sm

v
explored in more detail in the next section.)
4.3 Varia
The scope of a variable is the region of your program in which it is defined. A globa
variable has global scope -- it is
other hand, variables declared within a function are defined only within the body of th
function. They are local variables and have local scope. Function parameters also cou
as local variables and are defined only within the body of the function.
Within the body of a function, a local variable takes precedence over a global va
th the same name. If you declare a local variable or function parameter with thwi
name as a global variable, you effectively hide the global variable. Fo
following code prints the word "local":
v
var scope = "local"; // Declare a local variable with the same
name
document.write(scope); // Use the local variable, not the global
one
}
Although y
if you don't:
scope = "global"; // Declare a global variab
without var
function checkscope( ) {
scope = "local"; // Oops! We just changed the gl
levariab
document.writ
myscope = "lo
global variable
document.write
}

In general, functions do not know what variables are defined in the global scope or w
they are being used for. Thus, if a function uses a global variable instead of a loc
runs the risk of changing a value upon which some other part of the program relies.
Fortunately, avoiding this problem is simple: declare all variables with
hat
al one, it
In JavaScript 1.2 (and ECMAScript v3), function definitions can be nested. Each function
so it is possible to have several nested layers of local scope. For
e"; // A nested scope of local
);
lock-level scope. All
ion, no matter where they are declared, are defined
the following code, the variables i, j, and k all have the same
e the
= 0; // i is defined throughout
if (typeof o == "object") {
10
/ j is defined, but ay not be
can
rprising results. The following code illustrates this:
var.
has its own local scope,
example:
var scope = "global scope"; // A global variable
function checkscope( ) {
var scope = "local scope"; // A local variable
function nested( ) {
var scope = "nested scop
variables
document.write(scope); // Prints "nested scope"

}
nested( );
}
ckscope(che
4.3.1 No Block Scope
Note that unlike C, C++, and Java, JavaScript does not have b
variables declared in a funct
on. In throughout the functi
scope: all three are defined throughout the body of the function. This would not b
case if the code were written in C, C++, or Java:
function test(o) {
var i
unctionf
var j = 0; // j is defined everywhere, not
just block
for(var k = 0; k < 10; k++) { // k is defined everywhere, not
just loop
document.write(k);
}
document.write(k); // k is still defined: prints
}
document.write(j); / m
initialized
}
The rule that all variables declared in a function are defined throughout the function
cause su
var scope = "global";
function f( ) {
alert(scope); // Displays "undefined", not "global"
var scope = "local"; // Variable initialized here, but defined

everywhere
You might think that the first call to alert( ) would display "global", since the var
scope
function f( ) {
it has a value
ood programming practice to place all of your variable
ript
st kind of
ed
ndefined variable is one that has been declared but has never had a
value assigned to it. If you read the value of one of these variables, you obtain its default
The following code fragment illustrates some of the differences between truly undefined
alert(scope); // Displays "local"
}
f( );
statement declaring the local variable has not yet been executed. Because of the
rules, however, this is not what happens. The local variable is defined throughout the
body of the function, which means the global variable by the same name is hidden
throughout the function. Although the local variable is defined throughout, it is not
actually initialized until the
var statement is executed. Thus, the function f in the
previous example is equivalent to the following:
var scope; // Local variable is declared at the start of the
function
alert(scope); // It exists here, but still has "undefined"
value
scope = "local"; // Now we initialize it and give it a value
alert(scope); // And here
}
This example illustrates why it is g

declarations together at the start of any function.
4.3.2 Undefined Versus Unassigned
The examples in the previous section demonstrate a subtle point in JavaSc
programming: there are two different kinds of undefined variables. The fir
undefined variable is one that has never been declared. An attempt to read the value of
such an undeclared variable causes a runtime error. Undeclared variables are undefined
because they simply do not exist. As described earlier, assigning a value to an undeclar
variable does not cause an error; instead, it implicitly declares the variable in the global
scope.
The second kind of u
value,
undefined. This type of undefined variable might more usefully be called
unassigned, to distinguish it from the more serious kind of undefined variable that has not
even been declared and does not exist.
and merely unassigned variables:

Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×