Preface: In the 1. What is a closure? Simply put, a closure is a function whose characteristics are: a scope can access the local variables inside another function. Here is a simple example: For example, we now have a function, and we define a local variable inside it. If other scopes can access this local variable, a closure is generated. So we define another function inside this function to see if the function scope inside can access the local variables in the outer function. function f1(){ var num = 10; function f2(){ console.log(num); } f2(); } f1(); The printed result is: It can be found that the value is printed out successfully, so a closure is generated. We change the call of f2 function to the return value of f1 function, and then call f1 function outside the function, as follows: function f1(){ var num = 10; function f2(){ console.log(num); } return f2() } var f = f1(); f(); At this point, it is equivalent to the scope outside f1 accessing the variables of its internal function. The print result is: It can be found that the local variables inside it can also be used here, and closures are generated. So we can conclude that:
2. The role of closureWe know that the local variables defined inside a function can only be used inside the function, and they will be destroyed when we finish using them. However, with closures, this local variable will be used outside the function and will not be destroyed until its external caller has finished calling it. Therefore, the role of closures is to extend the scope of the variable. This is the end of this article about JavaScript closures. For more information about JavaScript closures, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future! You may also be interested in:
|
>>: Html Select uses the selected attribute to set the default selection
In the following example, when the width of the td...
This article example shares the specific code of ...
Preface If CSS is the basic skill of front-end de...
Perhaps when I name this article like this, someon...
Table of contents Preface Setting up with Vue CLI...
1. Create a sequence table CREATE TABLE `sequence...
WeChat applet trajectory playback mainly uses pol...
Table of contents ESLint plugin installation in H...
Project requirements require some preprocessing o...
Preface A reverse proxy is a server that receives...
MySQL uses triggers to solve the row limit of the...
After starting Docker, let's take a look at t...
Table of contents Preface Style Function Descript...
1. Overflow Overflow is overflow (container). Whe...
1. Download the image docker pull selenium/hub do...