Home > Web Front-end > JS Tutorial > Detailed explanation of JavaScript variable scope classification and usage techniques with examples

Detailed explanation of JavaScript variable scope classification and usage techniques with examples

伊谢尔伦
Release: 2017-07-18 10:23:51
Original
1270 people have browsed it

Variable scope is a topic that every programming language touches, and it is also a knowledge point that a programmer must master. Having a deep understanding of variable scope will help you write stable programs.

1. JavaScript scope classification
JavaScript has two scopes: global (window) and function level (function). Function level (function) should not be understood as "block level (braces {} level)".

2. Distinguish and define JavaScript global variables and local variables
1.1 Variables defined outside all functions, with or without the var keyword, are global variables. The global variable is actually parsed into an attribute of the window object, so we can access it in the "window.global variable name" method. It is recommended to use the variable name to access it directly unless necessary. The following example demonstrates the most common method of defining global variables:

var msg1='This is message 1'; 
msg2='This is message 2'; 
alert(window.msg1); //This is message 1 使用window关键字进行访问 
alert(window.msg2); //This is message 2 
alert(msg1); //This is message 1 省略window关键字的访问方式 
alert(msg2); //This is message 2 
function otherFunction(){} //其它一些函数或对象声明代码 
var otherObject={};
Copy after login


1.2 Global variables can also be defined and obtained within a function (local variable runtime environment). The method of definition is not to use the var keyword, and the global variable content can be easily obtained in the local environment, just use the global variable name to reference it. It should be noted that if a local variable with the same name as the global variable is defined in the function, then the function body will use its own local variable first. If you must use a global variable with the same name at this time, please add the window prefix. For example:

var msg1='This is message 1'; 
var msg3='This is message 3'; 
function otherFunction() 
{ 
msg2='This is message 2'; //不使用var关键字,其实也是定义一个全局变量 
var msg3='Message 3'; 
alert(msg1); //This is message 1 (函数内当然可以访问到外面定义的全局变量,再深的函数嵌套一样能正确获到这个全局变量,这是JavaScript闭包的其中一种体现) 
alert(msg3); //Message 3 (局部变量msg3) 
alert(window.msg3); //This is message 3 (使用window前缀访问同名的全局变量msg3) 
alert(this.msg3); //This is message 3 (因为otherFunction ()定义在一个全局的环境中,此时otherFunction ()的this也是指向window,所有你看到window. msg3是等于this. msg3的) 
} 
otherFunction(); 
//otherFunction函数外面定义的msg1和里面定义的msg2依然是全局变量 
alert(window.msg1); //This is message 1 
alert(window.msg2); //This is message 2
Copy after login


2.1 Using the var keyword, the variables defined in the function body are local variables. This variable can be used by all statement blocks ({}) and sub-functions below it. This variable can be accessed anywhere in this function, but cannot be accessed "directly" outside this function (closures allow indirect access, or proxy access, this knowledge point is beyond the scope of this article). For example:

function showMsg() 
{ 
if (true) 
{ 
var msg='This is message'; 
} 
alert(msg); //This is message 
} 
showMsg(); 
alert(typeof(msg)); //undefiend 
//这里在if {}大括号内定义的变量msg还能在if外showMsg()内访问到,但在showMsg()外则是无法访问的
Copy after login


2.2 The variables of the parent function can be accessed by the child function, but the variables of the child function cannot be accessed by the parent function. Obviously this is consistent with the function-level scope we mentioned at the beginning of. It seems that the father is more cheerful and the son is stingy. For example:

function showMsg() 
{ 
var MsgA='Message A'; 
this.setMsg=function(msg) 
{ 
var MsgB='Message B'; 
alert(MsgA); //Message A (子函数setMsg()可以访问父函数showMsg()的局部变量MsgA) 
} 
alert(MsgB); //MsgB未定义 (在父函数中不能访问其子函数中定义的变量MsgB) 
} 
var sm=new showMsg(); 
sm.setMsg('Message string');
Copy after login


3. Usage skills
1. In order to avoid variable confusion or overwriting, do not forget to add the var keyword to the definition of local variables (if necessary, we need to use the variable Take the initiative to release it after completion, that is, "variable name = null"). It is also recommended to define all variables at the beginning of each function body. Examples are as follows:

var msg='Message'; 
function showMsg() 
{ 
var msg; //这里即使不小心使用了与全局变量一样的变量名,也不用担心覆盖同名全局变量的问题 
var a; 
var b; 
var c; 
for (a=0;a<10;a++){} 
this.setMsg=function(){} 
}
Copy after login


2. Use anonymous functions skillfully to reduce naming conflicts or variable pollution. The following two pieces of code actually implement the same function, and the way the first piece of code is written is that you can boldly use the variable names you want to use in the anonymous function, etc., and you don't have to worry about the variables you define overwriting other people's definitions or your own definitions elsewhere. variable.

//定义一个匿名函数,然后把代码丢到这个匿名函数里面,能有效减少命名冲突或变量污染,这是常见JS框架的做法 
(function() 
{ 
var msg=&#39;This is message&#39;; 
alert(msg); 
})(); 
document.write(msg); //msg未定义 (匿名函数外的其它方法已无法调用msg这个变量) 
//----------------------------- 
var msg=&#39;This is message&#39;; 
alert(msg);
Copy after login


3. It is not recommended to use this instead of window to access global variables in functions that do not require instantiation. Normally functions using the this keyword should be treated as JavaScript classes (I like to prefix "cls" to the class name). If the following functions are only called as ordinary functions, the this keyword should not appear, because this is usually to operate a global variable. Example:

function clsMsg() 
{ 
this.msg=&#39;This is default message&#39;; 
this.showMsg=function() 
{ 
alert(this.msg); 
} 
} 
sMsg=new clsMsg(); 
sMsg.msg=&#39;This is new message&#39;; 
sMsg.showMsg();
Copy after login

The above is the detailed content of Detailed explanation of JavaScript variable scope classification and usage techniques with examples. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template