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
This article example shares the specific code of ...
XQuery is a language for extracting data from XML...
I have been in contact with PHP for so long, but ...
Table of contents Get the time in the past week G...
1. RPM package installation steps: 1. Find the co...
Table of contents 1. Introduction to v-slot 2. An...
In response to the popularity of nodejs, we have ...
The following is an introduction to using SQL que...
1. 85% of ads go unread <br />Interpretatio...
The first article on data backup and restoration ...
Table of contents Question 1: How are props used ...
Table of contents Preface text 1. Panel 2. Huaron...
Building an image is a very important process in ...
I had nothing to do, so I bought the cheapest Ali...
My system and software versions are as follows: S...