Javascript variable: Global? Or partial? Note This
In JS, there is no block-level scope.
Here are two examples:
If statement block:
if (true){var name='Ling';}alert(name);Output: Ling
For statement block;
for(var i=0;i<10;i++) {var name='Ling';}alert(i);alert(name);
Output: 10
Output: Ling
That is to say, the final result is the global variable under the window:
alert(window.i);alert(window.name);
In the Javascript function body, note the following situations: 1. Whether there is a Var
If Var exists, declare the variable as a local variable in the function. For example, the name data cannot be read.
function box(){var name ='Ling';}alert(name);If var is removed, the output will be: Ling. The declared variable is a global variable. In the process of writing code, if the initial variable is not applicable to var, there will be many accidents. Therefore, you must add var when writing the initial variable.
2. The names of global variables and local variables are the same.
var scope="global"; function t(){ alert(scope); var scope="local" alert(scope); } The final output result is:
Undefined
Local
Why is such a result? Because:
Javascript variable range
(1) The scope of global variables is global, that is, global variables exist everywhere in the Javascript program. Defined in the "script" block, outside the "function" function.
(2) The scope of a local variable is local. It is defined within a function or a function parameter. The scope of the variable is from the beginning to the end of the function. (note the following)
(3) In a function, the priority of a local variable is higher than that of a global variable with the same name. If a local variable with the same name (including parameters) exists ), the global variable will no longer work.
This is the reason. I don't know if you understand it ~~
So how can we solve this problem when the global and local variables are named again?
Haha ~~ The simplest thing is to avoid global variables and local variables ~~
Another method is to use the window. global variable name for all properties of the window object to have a global scope, as shown below:
var scope="global"; function t(){ alert(window.scope); var scope="local" alert(scope); }
At this point, the problem is over.
Summary
The above problem also reflects another problem. If the naming rules are not standardized, there will be many unexpected problems, spend some time surfing the internet to check several naming rules, which can reduce unnecessary troubles when writing code.