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

Jul 18, 2017 am 10:23 AM
javascript Scope skills

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Usage of typedef struct in c language Usage of typedef struct in c language May 09, 2024 am 10:15 AM

typedef struct is used in C language to create structure type aliases to simplify the use of structures. It aliases a new data type to an existing structure by specifying the structure alias. Benefits include enhanced readability, code reuse, and type checking. Note: The structure must be defined before using an alias. The alias must be unique in the program and only valid within the scope in which it is declared.

How to solve variable expected in java How to solve variable expected in java May 07, 2024 am 02:48 AM

Variable expected value exceptions in Java can be solved by: initializing variables; using default values; using null values; using checks and assignments; and knowing the scope of local variables.

Advantages and disadvantages of closures in js Advantages and disadvantages of closures in js May 10, 2024 am 04:39 AM

Advantages of JavaScript closures include maintaining variable scope, enabling modular code, deferred execution, and event handling; disadvantages include memory leaks, increased complexity, performance overhead, and scope chain effects.

What does include mean in c++ What does include mean in c++ May 09, 2024 am 01:45 AM

The #include preprocessor directive in C++ inserts the contents of an external source file into the current source file, copying its contents to the corresponding location in the current source file. Mainly used to include header files that contain declarations needed in the code, such as #include <iostream> to include standard input/output functions.

C++ smart pointers: a comprehensive analysis of their life cycle C++ smart pointers: a comprehensive analysis of their life cycle May 09, 2024 am 11:06 AM

Life cycle of C++ smart pointers: Creation: Smart pointers are created when memory is allocated. Ownership transfer: Transfer ownership through a move operation. Release: Memory is released when a smart pointer goes out of scope or is explicitly released. Object destruction: When the pointed object is destroyed, the smart pointer becomes an invalid pointer.

Can the definition and call of functions in C++ be nested? Can the definition and call of functions in C++ be nested? May 06, 2024 pm 06:36 PM

Can. C++ allows nested function definitions and calls. External functions can define built-in functions, and internal functions can be called directly within the scope. Nested functions enhance encapsulation, reusability, and scope control. However, internal functions cannot directly access local variables of external functions, and the return value type must be consistent with the external function declaration. Internal functions cannot be self-recursive.

The difference between let and var in vue The difference between let and var in vue May 08, 2024 pm 04:21 PM

In Vue, there is a difference in scope when declaring variables between let and var: Scope: var has global scope and let has block-level scope. Block-level scope: var does not create a block-level scope, let creates a block-level scope. Redeclaration: var allows redeclaration of variables in the same scope, let does not.

There are several situations where this in js points to There are several situations where this in js points to May 06, 2024 pm 02:03 PM

In JavaScript, the pointing types of this include: 1. Global object; 2. Function call; 3. Constructor call; 4. Event handler; 5. Arrow function (inheriting outer this). Additionally, you can explicitly set what this points to using the bind(), call(), and apply() methods.

See all articles