I believe you are familiar with global variables. A variable defined in the function scope with a=1 will be a global variable. In the global scope, you can use the following three forms to create a globally visible name:
Copy the code code as follows:
<script>
var a = 1;
b = 2;
window.c = 3;
</script>
For the method b=2, it is actually the same as c. 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 gives Window adds a property b and assigns a value.
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 code as follows:
<script>
alert(a);
var a=1;
</script>
Copy the code code as follows:
<script>
alert(a);//error, a undefined
a=1;
</script>