Concept of closure

Posted by jrforrester on Mon, 17 Jan 2022 22:00:10 +0100

How to generate closures

Closure means that function variables can be saved in the scope of the function, so it seems that the function "wraps" the variables// By definition, functions that contain variables are closures
That is, nested functions can be called closures

The scope deals with two special situations:
Functions are passed as arguments
Function is brought back as a return value

Application scenarios of closures

Closure application scenario 1 encapsulates the private properties and methods of objects

Hide data
Make a simple caching tool

// Closures hide data and only provide API s
function createCache() {
    const num=100
    const data = {} // The data in the closure is hidden and not accessed by the outside world
    return {
        num:num,
        set: function (key, val) {
            data[key] = val
        },
        get: function (key) {
            return data[key]
        }
    }
}

const c = createCache()
console.log(c.num)//num is now a c private attribute
c.set('a', 100) //set is now the private method of c
console.log( c.get('a') )

Closure application scenario 2, closure function callback function

		   <body>
			    <a href="#" id="as1">20</a>
			    <a href="#" id="as2">40</a>
			</body>
			<script>
			 function changeSize(size){
			     return function(){
			         document.body.style.fontSize=size+'px';
			     }
			 }
			 var size20=changeSize(20);
			 var size40=changeSize(40);
			
			 document.getElementById('as1').onclick=size20;
			 document.getElementById('as2').onclick=size40;
			
			</script>

Closure application scenario 3, function throttling and anti chattering

			<body>
			<!-- Function anti chattering refers to the delay after stopping triggering when the function is triggered by high frequency n Second to execute the function,
					(That is, each trigger clears the delay function and starts timing again),Generally used resize scroll,mousemove -->
			<!-- Function throttling principle delay when function is started at high frequency n It will be executed again after seconds. Anti shake is mainly triggered by the user after a time and delayed for a period of time,
					 Throttling will trigger an event within the specified event -->
			</body>
			<script>
			// 	Function throttling: to ensure that a function can be executed at most once in a specific time.
			//  Function anti shake: the function is executed after it is not called again within a specific time.
			//Anti shake
			var debounce = function(func, delay) {
			  var timer = null
			  return function() {
			      var that = this;
			      var args = arguments;
			       
			      if(timer) {
			          clearTimeout(timer);
			      }
			 
			      timer = setTimeout(function() {
			          func.apply(that, args);
			      }, delay)
			  }
			}
			 
			ipt.addEventListener('keyup', debounce(function(e){
			  console.log(e.target.value);
			}, 400))
			</script>

How to understand closure

1, What is a closure:

① To understand closures, first understand the special variable scope of javascript. There are only two kinds of variables: global variables and local variables.
② The special feature of javascript language is that the variables in the external scope can be read inside the function.
③ Sometimes we need to get the local variables in the function, but under normal circumstances, this cannot be read. At this time, we need to use closures. In javascript language, only the sub functions inside a function can read local variables, so closures can be simply understood as "functions defined inside a function". A closure is a function that has access to a variable in the scope of another function. Its essence is that the scope chain of a function holds references to external function variable objects.

II Application scenarios of closures:

① Functions are passed as arguments
② Function is returned as a return value
③ Practical application (hiding data): why hide data? Because ordinary users can only view and change data through APIs such as get and set, and can't directly change data to achieve the so-called effect of hiding data; jquery takes advantage of this feature and must call $ ajax() to access internal property methods.
When encapsulating functions (private properties and methods are required),
Function anti chattering and function throttling
Singleton mode

III Advantages of closures:

(1) Variables reside in memory for a long time
(2) Another is that variables can be reused without causing variable pollution
① Global variables can be reused, but it is easy to cause variable pollution. The same global variables are defined in different places, which will cause confusion. "
② Local variables are only valid within the local scope and cannot be reused, which will not cause variable pollution.
③ Closure combines the advantages of global variables and local variables. Variables can be reused without causing variable pollution

IV Disadvantages of closures:

Because closures will save the variables in the function in memory and consume a lot of memory, closures cannot be abused, otherwise it will cause performance problems of web pages and memory leakage in IE. The solution is to delete all unused local variables before exiting the function.
 

Topics: Front-end