Explore the similarities and differences between three ways of declaring global variables in JavaScript

  • 2020-03-30 00:41:33
  • OfStack

Variables and variable declarations are the most basic concepts in a language that beginners can quickly grasp. The same is true for declaring variables in JavaScript, which is as simple as var (keyword) + variable name (identifier).

Method 1

Var test;
Var test = 5; Note that this sentence cannot be included in a function, otherwise it is a local variable. This is the first way to declare a global variable.

Way 2

Test = 5;
Instead of using var, assign a value to the identifier test, which implicitly declares the global variable test. Even if the statement is inside a function, test becomes a global variable when the function is executed.

Methods 3

Window. The test;
Window. The test = 5; This approach is often used to expose functions globally after an anonymous function is executed. As the last sentence in query1.5

Window. jQuery = window.$= jQuery;

If you just used the variable test, there would be no difference between the three. For example: alert(test) will display 5. But the three approaches are different in some cases. Declare the three variables a1,a2 and a3 respectively in the above three ways.

A1 = 11;
Var a2 = 22;
Window. The a3 = 33;

1, for in window

For (a in the window) {
  If (a = = 'a1' | | a = = 'a2' | | a = = 'a3') {
    Alert (a)
IE6/7/8/9: only a3 pops up, indicating that global variables declared either way will not be retrieved when for in window.
Firefox/Chrome/Safari/Opera: a1, a2, a3 are pop-up, suggests three ways declared a global variable, through the for can get in the window.

2, the delete

Try {
  Alert (delete a1);
}catch(e){alert(' unable to delete a1')}

Try {
  Alert (delete a2);
}catch(e){alert(' unable to delete a2')}

Try {
  Alert (delete a3);
}catch(e){alert(' unable to delete a3')}

The results are as follows

< img border = 0 SRC = "/ / files.jb51.net/file_images/article/201312/201312030918277.jpg" >

As you can see,
1, delete a2 all browsers are false. That is, variables declared through var cannot be deleted, and all browsers behave the same. This is also mentioned in the rhino book.

2, through the window. The a3 declared global variables in IE6/7/8 are unable to delete, ie 9 / Firefox/Chrome/Safari/Opera can.

Both of these are different, but both return true when the in operation is used.

Alert (' a1 in Windows); / / true
Alert (' a2 'in Windows). / / true
Alert (' a3 in Windows); / / true
When opening the window closure of the object with, all browsers behave the same, as shown below

With (Windows) {
  {if (a1)
    Alert (a1); / / 11
  If (a2) {
    Alert (a2); / / 22
  If (a3) {
    Alert (a3); / / 33

Related articles: