In JavaScript, declaring a variable is a simple var (keyword) + variable name (identifier).
Mode 1
Note that the sentence cannot be contained within a function, otherwise it is a local variable. This is the first way to declare a global variable.
Mode 2
No var is used to assign a value directly to the identifier test, which implicitly declares the global variable test. Even though the statement is within a function, when the function is executed, test becomes a global variable.
Mode 3
12 |
window.test; window.test = 5; |
This approach is often used when an anonymous function is executed to expose some functions to the global. As the last sentence in JQuery1.5
1 |
window.jQuery = window.$ = jQuery; |
If you just use the variable test, there are three different ways. For example: Alert (test) will show 5. But there are three ways in which there is a difference in some cases. Declare three variable a1,a2,a3 in the above three ways respectively.
123 |
a1 = 11; var a2 = 22; window.a3 = 33; |
1,for in Window
12345 |
for (a in window) {      if (a== ' A1 ' | | a== ' A2 ' | | a== ' A3 ' ) { |
IE6/7/8/9: Only pop-up A3, stating that the global variables declared through the first, two ways are not available through the for in window.
The firefox/chrome/safari/opera:a1,a2,a3 all popped up, explaining the global variables declared in three ways, which are available through the for-in window.
2,delete
1234567891011 |
try {
alert(
delete a1);
}
catch
(e){alert(
‘无法delete a1‘
)} try
{
alert(
delete a2);
}
catch
(e){alert(
‘无法delete a2‘
)}
try
{
alert(
delete a3);
}
catch
(e){alert(
‘无法delete a3‘
)}
|
The results are as follows
can see that
1,delete A2 all browsers are false. That is, variables declared through Var cannot be deleted, and all browsers behave consistently. This is also mentioned in the Rhino book.
2, the global variables declared by window.a3 method cannot be deleted in IE6/7/8, but can be ie9/firefox/chrome/safari/opera.
Although the above two points are different, it returns true when the in operation is used.
123 |
alert( ‘a1‘ in window); //true alert( ‘a2‘ in window); //true alert( ‘a3‘ in window); //true |
When you open an object with the window closure, all browsers also behave the same, as follows
1234567891011 |
with
(window){
if
(a1){
alert(a1);
//11
}
if
(a2){
alert(a2);
//22
}
if
(a3){
alert(a3);
//33
}
}
|
JavaScript declares global variables three ways of difference