Javascript Global Variable and Local Variable
Javascript variables can be divided into Global Variable (global variable) and Local Variable (regional variable). The difference between these two variables lies in the position, method and calling area of the declaration. The advantage of using global variables is the convenience of calling, but some Sometimes in a specific function, there may be an independent script that uses local variables to ensure that the operation of the entire program is not affected. The following are the main differences and sample applications of the two variables.
- Global Variable : It can be declared within or outside the function, and can be called within the entire web page, so although there can be countless Global Variables with different names in the entire web page, there is only one independent Global Variable name. If the name is repeated, the variable value will be overwritten. When the web page is closed, Global Variable will also become invalid.
- Local Variable : It can only be declared through the keyword var in the function. Each different function can have the same Local Variable variable name. In other words, the Local Variable between each function does not interfere with each other and cannot Called in other places outside the function, when the function finishes its work, the Local Variable also becomes invalid.
Examples of Javascript Global Variable and Local Variable
function Test(){
var var1='A';
var2='B';
document.write('var1 in function='+var1+'<br>'); // output A
document.write('var2 in function='+var2+'<hr>'); // output B
}
var var3='C';
Test(); // call Test function
document.write('var2 not in function ='+var2+'<br>'); // Output B
document.write('var3 not in function='+var3+'<hr>'); // Output C
</script>
var2 in function=B
var2 not in function=B
var3 not in function=C
Post a Comment
0 Comments