Java Reference
In-Depth Information
2.
Load the page into your browser, and you'll see a series of six alert boxes appear.
3.
Click OK on each alert box to see the next alert. The fi rst two show the values of string1
and string2 Hello and Goodbye , respectively. Then you assign string2 the value that's
in string1 . The next two alert boxes show the contents of string1 and string2 ; this time
both are Hello .
4.
Finally, you change the value of string1. Note that the value of string2 remains unaffected.
The fi nal two alert boxes show the new value of string1 (Now for something different)
and the unchanged value of string2 (Hello).
The fi rst thing you do in the script block is declare your two variables: string1 and string2.
However, notice that you have assigned them values at the same time that you have declared them. This
is a shortcut, called initializing , that saves you typing too much code.
var string1 =”Hello”;
var string2 = “Goodbye”;
Note that you can use this shortcut with all data types, not just strings. The next two lines show the
current value of each variable to the user using the alert() function.
alert(string1);
alert(string2);
Then you assign string2 the value that's contained in string1. To prove that the assignment has
really worked, you again show the user the contents of each variable using the alert() function.
string2 = string1;
alert(string1);
alert(string2);
Next, you set string1 to a new value.
string1 = “Now for something different”;
This leaves string2 with its current value, demonstrating that string2 has its own copy of the data
assigned to it from string1 in the previous step. You'll see in later chapters that this is not always the
case. However, as a general rule, basic data types, such as text and numbers, are always copied when
assigned, whereas more complex data types, like the objects you come across in Chapter 4, are actually
shared and not copied. For example, if you have a variable with the string Hello and assign fi ve other
variables the value of this variable, you now have the original data and fi ve independent copies of the
data. However, if it was an object rather than a string and you did the same thing, you'd fi nd you still
have only one copy of the data, but that six variables share it. Changing the data using any of the six
variable names would change them for all the variables.
Finally, the alert() function is used to show the current values of each variable.
alert(string1);
alert(string2);
Search WWH ::




Custom Search