Detailed explanation of Javascript closures and applications

Detailed explanation of Javascript closures and applications

Preface

Javascript closures are generally difficult to understand during the learning process. This article introduces closures from the aspects of what closures are, common closure examples, closure functions, closure applications and closure problems. I hope it can bring you a deeper understanding. Please point out any inappropriateness. Thank you.

1. What is a closure?

A closure is a nested inner (child) function that references data in the parent function's scope, which creates a closure.

Key understandings:

1. Nested functions are required to generate closures
2. Closures are functions, and are nested inner functions
3. Functions inside closures must reference data in the parent function scope

If the above conditions are not met, closure cannot be generated. The following example illustrates this.

1.1 Closure satisfies conditional code

<script>
			function person(){
				var name='marshal';
				function student(){ //Declare child function console.log(name);//reference the variable name in the parent function scope
				}
			}
			person(); //Function execution, generating closure </script>      

insert image description here

1.2 Closure Generation Time

	<script>
			function person(){
				var name='marshal'; //When js executes this line, a closure is generated function student(){ //Declare child function console.log(name); //Reference variable name in parent function scope
				}
				student(); //Internal function is called in external function }
			person(); //Function execution, although the closure condition is met, no closure is generated </script>

insert image description here

Closure generation time: The nested sub-function code block references the data in the parent function scope, and the closure is generated when the context is created before the nested sub-function is executed. Or simply put, when the nested subfunction is executed externally, a closure is generated at this moment.

<script>
			function person(){
				var name='marshal';
				function student(){
					console.log(name); //This method contains closure code }
				return student;
			}
			var p=person();//Because the sub-function object is created, the first closure is generated at this time, and the sub-function student is returned to p. Since p does not disappear, the variable name referenced by the sub-function is stored in the memory until p=null is recycled p();//Execute the closure code block of the sub-function and output "marhsal"
			p(); //Execute the closure code block of the subfunction for the second time and output "marhsal"
			person(); //The second sub-function is created to call the object. At this time, the second closure is generated, but the sub-function student code block is not executed. </script>

2. Common closure examples

2.1 Subfunction passed as argument

<script>
			function setTimeoutTest(message,time){
				setTimeout(function(){
					alert(message); //The nested child function references the parent function variable message, generating a closure }, time);
			}  
			setTimeoutTest('prompt message',1000);
		</script>

2.2 Counter usage (function return)

<script>
				function count(){
					var i=1;
					function add(){
						i++;
						console.log(i);
					}
					return add;
				}
				var c=count();//Production closure c();//2
				c();//3
				c();//4
		</script>

3. Closure Effect

3.1 Closure Effect

1) The child function references the variables or functions of the parent function, and the life cycle is extended

2) Its variables or functions always exist, and the values ​​inside the function can be accessed from outside

<script>
			function count(){
				var i=1;
				function add(){
					i++;
					console.log(i);
				}
				return add;
			}
			var c=count();
			c();//2
			c(); //3 i's life cycle is extended </script>

4. Closure Application

4.1 Custom encapsulation js code

External js code out.js implements self-increment and self-decrement (function count(){
	var i=1;
	function add(){
		i++;
		console.log(i);
	}
	function subtract(){
		i--
		console.log(i);
	}
	window.count={
		add:add,
		subtract:subtract
	}
})();
Reference out.js code <script src=out.js></script>
		<script>
			count.add(); //2
			count.subtract(); //1
			count.subtract(); //0
		</script>

5. Closure Problem

5.1 Closures and this

<script>
     var name="marshal"; //Create global variables var person={
		 name:"leo",
		 getName:function(){ //Return anonymous function return function(){ //Return this.name
				return this.name; //Return string }
		 }
	 };
	 alert(person.getName()()); // Output marshal, internal functions cannot directly access external function this
	 
</script>

Workaround

<script>
	     var name="marshal";
			 var person = {
				 name:"leo",
				 getName:function(){
					 var that=this; //Save this to another variable that the closure can access return function(){
						return that.name;
					 }
				 }
			 };
			 alert(person.getName()()); //that points to person, not window
	</script>

5.2 Memory Leaks

When using closures, the dependent variable always exists, and the object needs to be dereferenced and set to null to ensure that its memory can be reclaimed when appropriate.

This is the end of this article about the detailed explanation of Javascript closures and applications. For more relevant js closures and applications, 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:
  • JavaScript Advanced Closures Explained
  • JavaScript Closures Explained
  • JavaScript Closures Explained
  • Javascript scope and closure details
  • Detailed explanation of JavaScript closure issues
  • Detailed explanation of js closure and garbage collection mechanism examples
  • Analysis of JS closure principle and its usage scenarios
  • Detailed explanation of the principle and function of JavaScript closure

<<:  Solution to the problem that Ubuntu cannot connect to the Internet in the virtual machine

>>:  MySQL Community Server 5.7.19 Installation Guide (Detailed)

Recommend

Specific use of Docker anonymous mount and named mount

Table of contents Data volume Anonymous and named...

Document Object Model (DOM) in JavaScript

Table of contents 1. What is DOM 2. Select elemen...

Docker installation tutorial in Linux environment

1. Installation environment Docker supports the f...

html base url tag

Its function is to set a global style. Then your s...

Detailed tutorial for installing mysql5.7.21 under Windows

This article shares the installation tutorial of ...

Explanation of nginx load balancing and reverse proxy

Table of contents Load Balancing Load balancing c...

How to export mysql table structure to excel

The requirements are as follows Export the table ...

CSS and CSS3 flexible box model to achieve element width (height) adaptation

1. CSS realizes fixed width on the left and adapt...

Let's talk about the storage engine in MySQL

Basics In a relational database, each data table ...

MySQL lock control concurrency method

Table of contents Preface 1. Optimistic Locking A...

Detailed explanation of keepAlive use cases in Vue

In development, it is often necessary to cache th...

favico.ico---Website ico icon setting steps

1. Download the successfully generated icon file, ...

Web page header optimization suggestions

Logo optimization: 1.The logo image should be as ...