Home Web Front-end JS Tutorial JavaScript variable scope and closure_javascript skills

JavaScript variable scope and closure_javascript skills

May 16, 2016 pm 06:48 PM
javascript Scope variable Closure

Scope JavaScript variable scope is divided according to functions. In order to quickly understand its characteristics, we will demonstrate it through an example.

Example 1:

<script type="text/javascript"> 
var i = 1; 
// 弹出内容为 1 true 的提示框 
alert(window.i + &#39; &#39; + (window.i == i)); 
</script>
Copy after login

Analysis:
The variables defined globally are actually the attributes of the window object.
As can be seen from the above example, when we define global variables, the window object will generate a corresponding attribute. How to prevent our code from generating this attribute? See the example below.
Example 2:

<script type="text/javascript"> 
var document = 1; 
window.onload = function(){ 
alert(document); 
} 
// 弹出内容为 1 的提示框 
alert(window.document); 
</script>
Copy after login

This is a situation we don’t want to see. We can do this:

<script type="text/javascript"> 
function test(){ 
var document = 1; 
window.onload = function(){ 
alert(document); 
} 
} 
test(); 
// 弹出内容为 [object] 的提示框 
alert(window.document); 
</script>
Copy after login

In order to make the code more concise, we can do this:

<script type="text/javascript"> 
(function(){ 
var document = 1; 
window.onload = function(){ 
alert(document); 
} 
})(); 
// 弹出内容为 [object] 的提示框 
alert(window.document); 
</script>
Copy after login

Analysis:
This form of running anonymous methods is often seen in mainstream JavaScript frameworks. This can avoid generating unnecessary attributes of the window object and reduce the possibility of conflicts.
Example 3:

<script type="text/javascript"> 
(function(){ 
if(&#39;1&#39; == &#39;1&#39;){ 
var i = 1; 
} 
// 弹出内容为 1 的提示框 
alert(i); 
})(); 
</script>
Copy after login

Analysis:
The scope of the variable is the entire function, not the {} block.
Example 4:

<script type="text/javascript"> 
var i = 1; 
// 弹出内容为 1 的提示框 
alert(i); 
var i = 2; 
// 弹出内容为 2 的提示框 
alert(i); 
</script>
Copy after login


Analysis:
A variable can be redefined, which seems a bit strange, because this does not work in many other languages.
Example 5:

<script type="text/javascript"> 
function test(){ 
i = 1; 
} 
test(); 
// 弹出内容为 1 的提示框 
alert(window.i); 
</script>
Copy after login

Analysis:
If an uninitialized variable is assigned a value, then this variable will be used as a global variable.

Example 6:

<script type="text/javascript"> 
window.onload = function(){ 
var i = 1; 
function test(){ 
alert(i); 
} 
// 弹出内容为 1 的提示框 
test(); 
} 
</script>
Copy after login

Analysis:
Internal functions can access variables of external functions, which leads to a new concept, that is closure.
Closure
What is a closure? Simply put, it is a function A whose internal function B can access the variables defined in A, even if function A has terminated. Let’s learn about it through examples.
Example 7:

<script type="text/javascript"> 
window.onload = function(){ 
var i = 1; 
window.onunload = function(){ 
alert(i); 
} 
} 
</script>
Copy after login

Analysis:
When the entire page is loaded, the onload event will be triggered. This onload event method registers a method for the onunload event of the window. In this method The variables declared in the onload event method are used, and then the onload event method ends. At this time, we click to close the window, and a prompt box with a content of 1 will pop up, indicating that the onunload event method successfully called the variables declared in the onload event method.
In order to further understand the characteristics of closures, look at the following example
Example 8:

<script type="text/javascript"> 
function initX(oarg){ 
// 定义一个变量 
var x = oarg; 
// 定义一个显示变量的方法 
var funGet = function(){ 
alert(x); 
} 
// 定义一个对变量进行修改的方法 
var funSet = function(iarg){ 
x = iarg; 
} 
// 返回这两个方法 
return [funGet,funSet]; 
} 
// 运行一个方法实例,返回值为包含 get 和 set 方法的数组 
var funArr = initX(1); 
// 得到 get 方法 
var funGet = funArr[0]; 
// 得到 set 方法 
var funSet = funArr[1]; 
// 运行 get 方法,显示initX方法实例内的 x 变量,结果为 1 
funGet(); 
// 运行 set 方法,对initX方法实例内的 x 变量进行赋值 
funSet(2); 
// 运行 get 方法,显示initX方法实例内的 x 变量,结果为 2 
funGet(); 
</script>
Copy after login

Analysis:
When the internal function calls the variable defined by the external function, in fact The reference is to the memory block of this variable, so when we call the internal function, the referenced variable value is the actual content of the current variable.
Although the closure function is powerful, it can also cause us trouble if we are not careful. See the example below.
Example 9:

<button id="main">run</button> 
<script type="text/javascript"> 
(function(){ 
var obj = document.getElementById("main"); 
var funArr = [&#39;onclick&#39;,&#39;onkeypress&#39;]; 
for(var i=0; i<funArr.length; i++){ 
var temp = funArr[i]; 
obj[temp] = function(){ 
alert(temp); 
} 
} 
})(); 
</script>
Copy after login

The original intention of writing the code is to register click events and key events for the button whose id is main. The content of the event is to pop up a prompt box with the event name respectively. But the result is a bit strange. The prompt boxes of the two events are all onkeypress. According to the principle of closure, if we analyze carefully, we will find that when the two event methods are called, the temp variable points to the content of funArr[1]. We can Modify this way to solve this problem:

<button id="main">run</button> 
<script type="text/javascript"> 
(function(){ 
var obj = document.getElementById("main"); 
var funArr = [&#39;onclick&#39;,&#39;onkeypress&#39;]; 
for(var i=0; i<funArr.length; i++){ 
(function(){ 
var temp = funArr[i]; 
obj[temp] = function(){ 
alert(temp); 
} 
})(); 
} 
})(); 
</script>
Copy after login

Put the code in the for loop into a function, so that each loop will generate a function instance and let the function instance record each value in the funArr array , thus avoiding the problems encountered above.

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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Hot Topics

Java Tutorial
1665
14
PHP Tutorial
1269
29
C# Tutorial
1249
24
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.

How to implement closure in C++ Lambda expression? How to implement closure in C++ Lambda expression? Jun 01, 2024 pm 05:50 PM

C++ Lambda expressions support closures, which save function scope variables and make them accessible to functions. The syntax is [capture-list](parameters)->return-type{function-body}. capture-list defines the variables to capture. You can use [=] to capture all local variables by value, [&] to capture all local variables by reference, or [variable1, variable2,...] to capture specific variables. Lambda expressions can only access captured variables but cannot modify the original value.

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.

See all articles