当前位置:网站首页>What is a closure function

What is a closure function

2022-06-23 09:14:00 Crazy_ GirlLL

What is a closure function
1、 Definition and Usage : When the return value of one function is another function , If the returned function calls other variables inside its parent function , If the returned function is executed externally , There's a closure .( The concept blogger excerpts the above points , View details     Baidu Encyclopedia )
2、 form : Enable the external function to call the variable defined inside the function .

Case study 1: According to the rules of the scope chain , The underlying scope has no declared variables , I'll go up to the next level , Find and return , If you don't find it, you keep looking for , until window The variable of , Return on no undefined. There are obvious variables here a It's internal to the function fun The variable of the a .

( Scope classification of variables : Global and local variables .)
* notes :* When variables are declared inside a function , Be sure to use var command . If not , You actually declare a global variable !

 Insert picture description here

Case study 2: Different from case one fun2 In closure object , Function called at this time nbfun2 It's just an internal function method , So we define a variable name After the closure function object is called , take nbfun2 The function is assigned to name Variable ; And then use name() Method .

 Insert picture description here

Case study 3:
First step : When we call a closure fun3 Object time , An introduction 1 An introduction 2 Give the returned function objects to the variables respectively a b;
The second step : At this point, the internal function call is output from the console Pass in separately 1 2 Value to a1 Of y b2 Of y;
( At this time, that is to say a1 b2 All are closures. They share the same function definitions , But it is stored in a different environment )
stay a1 in x=1, b2 in x=2;

 Insert picture description here
summary :

Closures are mainly used to design private methods and variables . The advantage of closures is that they can avoid the pollution of global variables , The disadvantage is that closures are memory resident , Increases memory usage , Improper use can easily cause memory leakage . stay js in , Function is closure , Only functions produce the concept of scope

Closures have three characteristics :

Function nested function
Functions can reference external parameters and variables internally
Parameters and variables are not recycled by the garbage collection mechanism

原网站

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