Instance 1:
Copy codeThe Code is as follows:
<Script type = "text/javascript">
Var I = 1;
// A prompt box with the content 1 true is displayed.
Alert (window. I + ''+ (window. I = I ));
</Script>
Analysis:
The global variables are actually the properties of the window object.
The above example shows that while we define global variables, the window object will generate a corresponding attribute. How can we prevent this attribute from being generated by our code? See the following example.
Example 2:
Copy codeThe Code is as follows:
<Script type = "text/javascript">
Var document = 1;
Window. onload = function (){
Alert (document );
}
// A prompt box with content 1 is displayed.
Alert(registry.doc ument );
</Script>
In this case, we don't want to see it. We can do this:
Copy codeThe Code is as follows:
<Script type = "text/javascript">
Function test (){
Var document = 1;
Window. onload = function (){
Alert (document );
}
}
Test ();
// A prompt box with the content of [object] is displayed.
Alert(registry.doc ument );
</Script>
To make the code more concise, we can do this:
Copy codeThe Code is as follows:
<Script type = "text/javascript">
(Function (){
Var document = 1;
Window. onload = function (){
Alert (document );
}
})();
// A prompt box with the content of [object] is displayed.
Alert(registry.doc ument );
</Script>
Analysis:
This form of running anonymous methods is often seen in mainstream JavaScript frameworks. This can avoid unnecessary window object attributes and reduce the possibility of conflict.
Example 3:
Copy codeThe Code is as follows:
<Script type = "text/javascript">
(Function (){
If ('1' = '1 '){
Var I = 1;
}
// A prompt box with content 1 is displayed.
Alert (I );
})();
</Script>
Analysis:
The scope of the variable is the entire function, not the {} block.
Example 4:
Copy codeThe Code is as follows:
<Script type = "text/javascript">
Var I = 1;
// A prompt box with content 1 is displayed.
Alert (I );
Var I = 2;
// A prompt box with content 2 is displayed.
Alert (I );
</Script>
Analysis:
A variable can be redefined, which seems a bit strange, because it does not work in many other languages.
Example 5:
Copy codeThe Code is as follows:
<Script type = "text/javascript">
Function test (){
I = 1;
}
Test ();
// A prompt box with content 1 is displayed.
Alert (window. I );
</Script>
Analysis:
If you assign values to a variable that is not initialized, the variable is used as a global variable.