Home Web Front-end JS Tutorial Summary of js closure examples_basic knowledge

Summary of js closure examples_basic knowledge

May 16, 2016 pm 04:31 PM
js Example Closure

Js closure
Things to know before closure
1. Function scope
(1) The special thing about Js language is that global variables can be read directly inside the function

Copy code The code is as follows:


If in php

Copy code The code is as follows:

$n=100;
function parent(){
echo $n;
}
parent();//will report an error n is undefined
?>

(2). Local variables within the function cannot be read outside the function

Copy code The code is as follows:


Note that var must be added when declaring variables inside a function, otherwise a global variable will be declared

Copy code The code is as follows:

function parent(){
m=50;
}
parent();
alert(m);//50

//Of course this is even more true in php,

Copy code The code is as follows:

function parent(){
global $m;//global, definition and assignment should be separated
$m=50;
}
parent();
echo $m;//50
?>
//If there is no global, an undefined error will still be reported

Sometimes, if you need to get the local variables inside the function, you need to use a flexible method to take advantage of the characteristics of js variable scope, such as defining a sub-function inside the function. For the sub-function, the parent function is its global, and the sub-function is Functions can access variables in the parent function (which are local variables for the entire js code)

Copy code The code is as follows:


All local variables inside Parent are visible to its child functions, but local variables within its child functions are not visible to its parent function. This is the unique chain scope structure of js. Child objects will Search all the variables of the parent object upwards one level at a time. All variables of the parent object are visible to the child objects, and the reverse is not true! The son function above is a closure
Some students may be like this

Copy code The code is as follows:

function parent(){
var m=50;
function son(){
alert(m);
}
}
parent();
son()//Report function son is undefined

Note that in JavaScript, functions declared in functions are local and are released after the function is finished running
Pay attention to the difference between this and php

Copy code The code is as follows:

function parent(){
function son(){
$m=50;
echo $m;
}
}
parent();
son();//Output 50 and no error will be reported
?>

Closure

Define the function inside the function, the bridge connecting the inside and outside of the function
Closure has two functions:
One is the previously mentioned reading of variables inside the function,
The second is to store the values ​​of these variables in memory to achieve data sharing
Here are a few examples of closures

Copy code The code is as follows:


The execution result of the anonymous function (that is, the declaration of the inner sub-function is assigned to the global variable cut), i is saved in the memory
When executing cut(), the value is obtained directly from the memory. i can only be called by the cnt() function, and direct alert(i) will not work
You can also pass parameters into the closure

Copy code The code is as follows:

var cnt=(function(num){
return function(){
alert(num);
num ;
}
})(5);
cnt();//5
cnt();//6
cnt();//7
//Of course, you can also pass parameters when calling
var cnt=(function(){
var i=0;
return function(num){
num =i;
alert(num);
i ;
}
})();
cnt(1);//1
cnt(2);//3
cnt(3);//5

In order to have a better understanding of closures, let’s look at the following code
For example, I want to return an array. There are 5 functions in the array. The first function pops up 0, the second pops up 1...
If the code is written like this

Copy code The code is as follows:

function box(){
var arr=[];
for(i=0;i<5;i ){
arr=function(){return i;}
}
return arr;
}
var a=box();
alert(a);//Array containing five function bodies
alert(a[0]());
alert(a[1]());

Pop-up function body
function(){return i;} }
The last i is 4, and then it becomes 5
For loop stops
I found that 5 pops up in all cases, which obviously does not meet our requirements

Solution 1
Self-immediate execution of functions inside

Copy code The code is as follows:

function box(){
var arr=[];
for(i=0;i<5;i ){
arr=(function(num){return i;})(i);
}
return arr;
}
var a=box();
for(var i=0;i alert(a);
}

But we found that the elements in the returned array are the results of function execution, but what we want is that the function has to upgrade our code

Solution 2
Closure implementation

Copy code The code is as follows:

function box(){
var arr=[];
          for(var i=0;i<5;i){

arr=(function(num){
Return function(){return num;}
                  })(i);

}
return arr; 
}

var arr=box();

for(var i=0;i<5;i ){

alert(arr());//0,1,2,3,4
}

Key code

Copy code The code is as follows:

arr=(function(num){
           return function(){return num;}
})(i);


When i=0
arr[0]=(function(num){return function(){return num;}})(0);

1 o’clock


arr[1]=(function(num){return function(){return num;}})(1);

The above are the benefits of closure! It's very simple and practical.

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)

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

What is the meaning of closure in C++ lambda expression? What is the meaning of closure in C++ lambda expression? Apr 17, 2024 pm 06:15 PM

In C++, a closure is a lambda expression that can access external variables. To create a closure, capture the outer variable in the lambda expression. Closures provide advantages such as reusability, information hiding, and delayed evaluation. They are useful in real-world situations such as event handlers, where the closure can still access the outer variables even if they are destroyed.

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.

What are the advantages and disadvantages of closures in C++ functions? What are the advantages and disadvantages of closures in C++ functions? Apr 25, 2024 pm 01:33 PM

A closure is a nested function that can access variables in the scope of the outer function. Its advantages include data encapsulation, state retention, and flexibility. Disadvantages include memory consumption, performance impact, and debugging complexity. Additionally, closures can create anonymous functions and pass them to other functions as callbacks or arguments.

The relationship between js and vue The relationship between js and vue Mar 11, 2024 pm 05:21 PM

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.

The impact of function pointers and closures on Golang performance The impact of function pointers and closures on Golang performance Apr 15, 2024 am 10:36 AM

The impact of function pointers and closures on Go performance is as follows: Function pointers: Slightly slower than direct calls, but improves readability and reusability. Closures: Typically slower, but encapsulate data and behavior. Practical case: Function pointers can optimize sorting algorithms, and closures can create event handlers, but they will bring performance losses.

Chained calls and closures of PHP functions Chained calls and closures of PHP functions Apr 13, 2024 am 11:18 AM

Yes, code simplicity and readability can be optimized through chained calls and closures: chained calls link function calls into a fluent interface. Closures create reusable blocks of code and access variables outside functions.

How are closures implemented in Java? How are closures implemented in Java? May 03, 2024 pm 12:48 PM

Closures in Java allow inner functions to access outer scope variables even if the outer function has exited. Implemented through anonymous inner classes, the inner class holds a reference to the outer class and keeps the outer variables active. Closures increase code flexibility, but you need to be aware of the risk of memory leaks because references to external variables by anonymous inner classes keep those variables alive.

See all articles