Thứ Tư, 21 tháng 8, 2013

VARIABLES

 Every variable is simply a named placeholder for a value.
var message;
This code defines a variable named messagethat can be used to hold any value.
var message = “hi”;
Here, messageis defined to hold a string value of “hi”. Doing this initialization doesn’t mark
the variable as being a string type; it is simply the assignment of a value to the variable. It is still
possible to not only change the value stored in the variable but also change the type of value, such
as this:
var message = “hi”;
message = 100; //legal, but not recommended
In this example, the variable message is first defined as having the string value “hi”and then
overwritten with the numeric value 100. Though it’s not recommended to switch the data type that
a variable contains, it is completely valid in ECMAScript.
It’s important to note that using the varoperator to define a variable makes it local to the scope in
which it was defined. For example, defining a variable inside of a function using varmeans that the
variable is destroyed as soon as the function exits, as shown here:
function test(){
var message = “hi”; //local variable
}
test();
alert(message); //error!
Here, the message variable is defined within a function using var. The function is called test(),
which creates the variable and assigns its value. Immediately after that, the variable is destroyed so
the last line in this example causes an error. It is, however, possible to define a variable globally by
simply omitting the varoperator as follows:
function test(){
message = “hi”; //global variable
}
test();
alert(message); //”hi”
By removing the var operator from the example, the message variable becomes global. As soon as the function test()is called, the variable is defined and becomes accessible outside of the function once it has been executed.
Although it’s possible to define global variables by omitting the varoperator, this approach is not recommended. Global variables defined locally are hard to maintain and cause confusion, because it’s not immediately apparent if the omission of varwas intentional. Strict mode throws a ReferenceErrorwhen an undeclared variable is assigned a value.If you need to define more than one variable, you can do it using a single statement, separating each variable (and optional initialization) with a comma like this:
var message = “hi”, 
found = false,
age = 29;
Here, three variables are defined and initialized. Because ECMAScript is loosely typed, variable initializations using different data types may be combined into a single statement. Though inserting line breaks and indenting the variables isn’t necessary, it helps to improve readability.When you are running in strict mode, you cannot define variables named evalor arguments. Doing so results in a syntax error.

Không có nhận xét nào:

Đăng nhận xét