Home >Web Front-end >JS Tutorial >In-depth analysis of the difference between Javascript global variables var and non-var_Basic knowledge

In-depth analysis of the difference between Javascript global variables var and non-var_Basic knowledge

WBOY
WBOYOriginal
2016-05-16 17:10:191201browse

I believe you are familiar with global variables. A variable defined in the form of a=1 in the function scope will be a global variable. In the global scope, the following three forms can be used to create a variable that is globally visible. Naming:

Copy code The code is as follows:

<script><br>var a = 1;<br>b = 2;<br>window.c = 3;<br></script>

For b=2, it is actually the same as c Yes, when executing this assignment statement, it will look for a variable named b along the scope chain. It has not found it until it reaches the top of the scope chain, so it adds a property b to the window and assigns it.

There are two differences between var and non-var:

1 The global variable of var cannot be deleted, because delete intelligently deletes the deletable attributes of the object, and the global attributes defined by var will be marked as non-deletable. It should be noted that if delete is unsuccessful, an error will not be thrown. The return value of delete is true|false.

2 Global variables defined by var will be promoted, but global variables defined without var will not be promoted. You can see the execution results of the following program:

Copy the code The code is as follows:

<script> <br>alert(a);<br>var a=1;<br></script>

Copy code The code is as follows: