当前位置:网站首页>Briefly introduce closures and some application scenarios

Briefly introduce closures and some application scenarios

2022-07-07 11:17:00 InfoQ

Closure

Preface

I was growing up , When a schoolgirl was interviewed , I heard the term closure for the first time . At that time, I heard some senior students explain ( I didn't quite understand it ), But I think , It seems very advanced .

Now after a year , I also deal with closures , Finally, I can talk about my understanding of it .

What is a closure ?

What is a closure ? —— It can be simply understood as :
Functions that have access to variables in the scope of another function are closures .

Let's start with an example :

function drink() {
 var beerName = " Snow Beer ";
 let beerNum1 = 1;
 const beerNum2 = 2;
 var innerBeer = {
 getBeer:function() {
 console.log(beerNum1)
 return beerName
 },
 setBeer:function(newBeer) {
 beerName = newBeer
 }
 }
 return innerBeer
}
var go = drink();
go.setbeer(" Stuffy donkey ");
go.getBeer();
console.log(go.getBeer())

When we use getBeer And setBeer When you use these two functions , There are no variables inside them beerNum1 And beerName Of , So what will they do at this time , Small partners who have learned scope chain may understand , At this time, they will go to the outer layer to find , That is to say drink Function to find , eureka , So it can be used .

But what? , Here comes the question ,drink Is a function , Its scope is called function scope , stay drink Function execution finished , This scope is to be destroyed , So at this point ,innerBeer How to do it ?

Or because of the scope chain , Even if drink It's done , When innerBeer When the two methods under it are called again , It uses variables , It cannot be destroyed , in other words ,beerNum1 And beerName Forced to become
Nail house
.

innerBeer: I just need to use , You can't destroy !

And this , It's a closure .

Closure : I am what I am

Why closures are prone to memory leaks ?

First of all, we need to know a concept : What is memory leak ?

When a variable that cannot be recycled is generated in memory , It is called memory leak

Let's look at the example just now ,
var go = drink();

go Is a global variable , You can call at any time setBeer And getBeer, Because we assign the return value of the function to it , As long as the page is not destroyed , It will always exist . and setBeer Follow getBeer It's going to be used again beerNum1 And beerName, That is what we mentioned above , Nail household theory . combination JavaScript Garbage collection mechanism , We now know , The two nail households cannot be removed .

This being beerNum1 And beerName Of memory , Only setBeer And getBeer To access , No one else can visit . And it does not belong to any execution context , So it can't be destroyed .

So say ,
Closures are prone to memory leaks

As long as the page doesn't close , This variable has been , Cause the problem of memory leakage

Why use closures ?

Zhang San ( That's right, it's Ben San, an outlaw maniac ) That's it :
Since closures can cause memory leaks , Then why should we use it ?

It's not because , We
In some cases , We hope that the variables in some functions will not be destroyed after the function is executed
( I know that too. , There seems to be a hint of sword ).

Zhang San has another question : Then why not define it as a global variable ? Now you can't recycle .

If you create a global variable , It is easy to be polluted , Variable with the same name , Or be modified by some functions . In order to avoid it being tampered with , And want to keep it for a long time , Make it look like a global variable , You can use it at any time , We will be at this time , Using closures !

Please note that : Closures must be used with caution

Application of closures

Checked several applications of closures , To learn ing

  • Mimic block level scope
  • An application of timer

 for (var i = 0; 1 < 10; i++) {
 (function (j) {
 setTimeout(function () {
 console.log(j);
 }, 1000 * j)
 })(i)
 }

  • Print a set of li The subscript

 for(var i = 0; i < lis.length; i++) {
 (function(j) {
 lis[j].onclick = function() {
 alert(j)
 }
 })(i)
 }

  • Buried point counter
  • The product is a common data collection method for website analysis

 function count() {
 var num = 0;
 return function() {
 return ++num
 }
 }
 var getNum = count(); //  The first place that needs statistics
 var getNewNum = count(); // The second place that needs statistics
 //  If we count two button Of hits
 document.querySelectorAll('button')[0].onclick = function() {
 console.log(' Click button 1 The number of times :'+getNum());
 }
 document.querySelectorAll('button')[0].onclick = function() {
 console.log(' Click button 2 The number of times :'+getNewNum());
 }

  • currying
  • The method of transforming a multi parameter function into a single parameter function , Make it more flexible and convenient

 //  Primitive function   Used to check whether the text conforms to the specification
 // reg  The regular expression passed in  txt  Text to be detected
 function check(reg,txt){
 return reg.test(txt)
 }
 console.log(check( Regularity of phone numbers ,13923456789));
 console.log(check( Regular mailbox ,[email protected]));
 
 //  Today,
 function nowCheck(reg){
 return function(txt){
 return reg.test(txt)
 }
 }
 var isPhone = nowCheck( Regularity of phone numbers )
 console.log(isPhone('13923456789'))
 var isEmail = nowCheck( Regular mailbox )
 console.log(isEmail('[email protected]'))

summary : To put it simply, closures

The cause of closures

The local variables in the function will be destroyed after the function is executed , occasionally , We don't want this local variable to be destroyed , We also want to conduct continuous operation and access externally , We'll use closures .

Why not create a global variable to replace this local variable ?

Because global variables will be polluted or modified .

Closures can access variables inside , Because of the scope chain , Used in function nesting , The idea that internal functions can access variables in the scope of parent functions .

Closures can cause memory leaks

Page not closed , Variables are always , Cannot be recycled by garbage collection mechanism or manually cleared .
原网站

版权声明
本文为[InfoQ]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207070909198649.html