Home  >  Article  >  Web Front-end  >  Incorrect use of var in javascript causes undefined_javascript tips

Incorrect use of var in javascript causes undefined_javascript tips

WBOY
WBOYOriginal
2016-05-16 15:07:131252browse

In JavaScript, variables are divided into local variables and global variables according to their different scopes. Variables defined directly are global variables, and global variables can be accessed by all scripts; variables defined in functions are local variables, and local variables only Valid within functions.
If global variables and local variables use the same variable name, the local variable will overwrite the global variable.
Example code:

<!DOCTYPE html> 
<html> 
  <head> 
    <meta charset="utf-8"> 
    <title>js中全局变量与局部变量</title> 
  </head> 
  <body> 
    <script type="text/javascript"> 
      var a = "全局变量"; 
      function test1() 
      { 
        var a = "局部变量"; 
         
        alert(a); 
      } 
       
      function test2() 
      { 
        alert(a); 
         
        var a = "局部变量"; 
         
        alert(a); 
      } 
       
      function test3() 
      { 
        alert(a); 
         
        a = "局部变量"; 
         
        alert(a); 
      } 
    </script> 
     
    <input type="button" value="test1" onclick="test1()"/> 
    <input type="button" value="test2" onclick="test2()"/> 
    <input type="button" value="test3" onclick="test3()"/> 
 
  </body> 
</html> 

The result of the operation is as follows:
Click test1 to pop up local variables.
Click test2, undefined pops up, and then local variables pop up

Click test3 to pop up the global variables, and then pop up the local variables

This is the difference between using var and not using it:
If you use var, then the program will force a new variable to be defined.
If var is not used, The system will first search whether the variable exists in the current context, and will only redefine a new variable if it does not exist.

In test3, the variables a used are all global variables. The first time the global variable is directly output, the second time is used after directly assigning a value to the global variable.
In both test1 and test2, using var to define a new variable with the same name in the function will cause the variables in the function to overwrite the global variable. So in test2: the first output a is the local variable a that has been overwritten, but no initial value is given, so the result undefined will appear. Using variables in this way is actually wrong and should be avoided.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn