1. Closure In For example, the following code: function f1() { var n = 999; function f2() { console.log(n); } return f2; } var result = f1(); result();//999 Function f2 is included in function f1, and all local variables in f1 are visible to f2. But the reverse is not true. The local variables inside f2 are not visible to f1. This is the " Since f2 can read the local variables in f1, as long as f2 is used as the return value, its internal variables can be read outside f1. 2. Closure usage scenarios1.setTimeout The first function passed by the native function f1(a) { function f2() { console.log(a); } return f2; } var fun = f1(1); setTimeout(fun,1000);//Print out 1 after one second 2. CallbackDefine a behavior and associate it with a user event (click or keypress). Code is usually bound to an event as a callback (a function that is called when the event is triggered). For example, the following code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Test</title> </head> <body> <a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="size-12">12</a> <a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="size-20">20</a> <a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" id="size-30">30</a> <script type="text/javascript"> function changeSize(size){ return function(){ document.body.style.fontSize = size + 'px'; }; } var size12 = changeSize(12); var size14 = changeSize(20); var size16 = changeSize(30); document.getElementById('size-12').onclick = size12; document.getElementById('size-20').onclick = size14; document.getElementById('size-30').onclick = size16; </script> </body> </html> When you click on a number, the font size will change to the corresponding size. 3. Function anti-shakeThe callback is executed n seconds after the event is triggered. If it is triggered again within n seconds, the timing is restarted. The key to the implementation lies in the As shown in the following code: /* * fn [function] the function that needs anti-shake* delay [number] milliseconds, anti-shake deadline value*/ function debounce(fn,delay){ let timer = null //With the help of closure return function() { if(timer){ clearTimeout(timer) //Entering this branch statement indicates that a timing process is currently in progress and the same event is triggered again. So to cancel the current timing and restart the timing timer = setTimeOut(fn,delay) }else{ timer = setTimeOut(fn,delay) // Entering this branch means that there is no timing currently, so start a timing} } } 4. Encapsulate private variablesAs shown in the following code: Create a counter using js Method 1: function f1() { var sum = 0; var obj = { inc:function () { sum++; return sum; } }; return obj; } let result = f1(); console.log(result.inc());//1 console.log(result.inc()); //2 console.log(result.inc());//3 In the returned object, a closure is implemented, which carries the local variable x, and the variable x cannot be accessed from external code at all. Method 2: function f1() { var sum = 0; function f2() { sum++; return f2; } f2.valueOf = function () { return sum; }; f2.toString = function () { return sum+''; }; return f2; } //Execute function f1, and return function f2 console.log(+f1());//0 console.log(+f1()()) //1 console.log(+f1()()()) //2 All js data types have the two methods
In numerical operations, This is the end of this article about the usage scenarios of Javascript closures. For more relevant Javascript closure content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future! You may also be interested in:
|
<<: Tudou.com front-end overview
>>: What is Software 404 and 404 Error and what is the difference between them
Recently, I was adding a series of statistical fu...
Table of contents Preface 1. Object.freeze() 2. O...
For Windows User Using openGauss in Docker Pull t...
1. High degree of collapse In the document flow, ...
Table of contents Single Node Diff reconcileSingl...
Table of contents Special characters in URLs URL ...
This article example shares the specific code of ...
Linux installation JDK1.8 steps 1. Check whether ...
CocosCreator realizes skill CD effect There are s...
Table of contents Class Component Functional Comp...
Table of contents 1. Parent component passes valu...
Use HTML color blocks to dynamically display data...
Table of contents 1. MySQL wildcard fuzzy query (...
Today, CSS preprocessors are the standard for web...
Table of contents Updatable Views Performance of ...