1. What is a closure?
So using closures, you can associate data with functions that operate on that data. For example: function foo() { let a = 1; return function() { console.log(a); } } let foo1 = foo(); foo1() // Output 1 This is an example of a closure. In foo, because a function is returned, this function has a closure covering the internal scope of foo, that is, a, so that a always survives and will not be recycled when foo ends. 2. The role of closures2.1) MemoryWhat is the memory property of closures? When a closure is generated, the state of the environment in which the function is located will always remain in the memory and will not be reclaimed by the garbage collection mechanism after the outer function call ends. For example: function foo() { let a = 0; return function() { a++; console.log(a); } } let foo1 = foo(); let foo2 = foo(); foo1(); // 1 foo2(); // 1 foo2(); // 2 foo1(); // 2 Because a is part of the closure, when the closure is generated, the environment state of a will be kept in the memory and will not be cleared after the outer function call ends. Therefore, as foo1 is used, the value of a in the memory will increase by 1. 2.2) Simulating private variablesEnsure that a variable can only be operated on by specified operations. For example : function foo() { let A = 0; return { getA : function() { return A; }, add : function() { A++; }, del : function() { A --; } } } let foo1 = foo(); console.log(foo1.getA()); // 0 foo1.add(); console.log(foo1.getA()); // 1 foo1.del(); console.log(foo1.getA()); // 0 Through closure, it is ensured that A can only be subjected to the specified addition and subtraction operations. 3. Notes on closuresClosures should not be abused, otherwise they may cause performance problems on the web page due to excessive memory usage, and may even cause memory leaks. SummarizeThis article ends here. I hope it can be helpful to you. I also hope you can pay more attention to more content on 123WORDPRESS.COM! You may also be interested in:
|
>>: Summary of Docker Consul container service updates and issues found
Disadvantages of Tables 1. Table takes up more byt...
1. Vector Map Vector graphics use straight lines ...
A status code that indicates a provisional respon...
Table of contents 1. Structural instructions Modu...
<br />Adding pictures reasonably can make a ...
As we all know, the CSS position absolute is set ...
Call How to call Amap API? The official open docu...
In the MySQL database, when we need fuzzy query, ...
Table of contents 1. Replace the apply method, ge...
Preface This article will focus on the use of Typ...
Preface Hello everyone, this is the CSS wizard - ...
Here 123WORDPRESS.COM presents the first part of ...
Preface When using Docker in a production environ...
Table of contents 1. Baidu Map API Access 2. Usin...
Table of contents Join syntax: 1. InnerJOIN: (Inn...