Learn about JavaScript closure functions in one article

Learn about JavaScript closure functions in one article

Variable Scope

To understand JavaScript closures, you must first understand JavaScript variable scope.

There are two types of variable scopes: global and local (global variables and local variables)

In JavaScript, global variables can be read directly inside a function.

var n=10
function fn(){
	alert(n)
}
fn() //10

The variables inside a function cannot be read from outside the function.

function fn(){
	var n=10;
}
fn()
alert(n) //n is not defined The function cannot read n from outside the function

Note: When var is used to declare a variable inside a function, the variable is a local variable. If var is not used, the variable is a global variable.

For example:

function fn(){
	n=10;
}
fn()
alert(n) //10

In addition, the function parameters are also local and only work within the function.

Under normal circumstances, we cannot get the local variables inside a function. The only workaround is to declare another function inside the function.

function f1(){
	var n=10;
	function f2(){
		alert(n)
	}
}

The f2 function can get all the local variables within the f1 function, but the f1 function cannot get the local variables inside the f2 function - the "chain scope" structure unique to the JavaScript language. (That is, the child object will search for the variables of all parent objects one level at a time), so all variables of the parent object are visible to the child object.

The f2 function can obtain the local variables of the parent function f1. If the f2() function is returned, the variables inside the f1() function can be accessed from outside the f1 function.

For example:

function f1(){
	var n=10;
	function f2(){
		alert(n)
	}
	return f2()
}
f1() //page popup 10

The f2() function in the example is a closure function.

The concept of closure

Due to scope reasons, we cannot access the variables defined in a function from outside the function, but sometimes we have this need, so the concept of closure appears.

A closure is a function that has access to variables in the scope of another function.

In the above example, the inner function f2 is a closure function.

In essence, a closure is a bridge that connects the inside of a function with the outside of the function.

Closure is a mechanism for protecting private variables. It forms a private scope when a function is executed, protecting the private variables inside from external interference.

Uses of closures

(1) You can read variables inside the parent scope function;

(2) The value of the variable is always stored in the memory (making the local variable a global variable) and is not cleared by the garbage collection mechanism.

Disadvantages of Closures

Since closures save all variables in the function into memory and the garbage collection mechanism does not clean them up, memory consumption is very large. Therefore, closures should not be abused, otherwise memory leaks may occur.

Replenish:

What is a memory leak?

Programs require memory to run. Whenever a request for memory is made, the operating system must supply it.
When some code variables in the application no longer need to use memory, but are not reclaimed by the operating system or the available memory pool, it means that a memory leak has occurred.

That is, when a piece of memory is no longer needed, it still exists - memory leak

Solve the problem of memory leak caused by closure:

Before exiting the function, delete all unused local variables.

For example, if you set the value of the current variable to 'null', when the garbage collection mechanism starts, these variables with values ​​of 'null' will be automatically recycled.

Finally, let's summarize the advantages and disadvantages of closures.

benefit

① Protect the security of variables within the function, implement encapsulation, and prevent variables from flowing into other environments and causing naming conflicts

② Maintain a variable in memory for caching (but excessive use is also a disadvantage, consuming memory)

③Anonymous self-executing functions can reduce memory consumption

harm

① One of the points has been reflected above, that is, the referenced private variables cannot be destroyed, which increases memory consumption and causes memory leaks. The solution is to manually assign it to null after using the variable;

②Secondly, since closures involve cross-domain access, it will cause performance loss. We can reduce the impact on execution speed by storing cross-scope variables in local variables and then directly accessing local variables.

Summarize

This is the end of this article about JavaScript closure functions. For more relevant JavaScript closure function 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:
  • JavaScript Closures Explained
  • Javascript scope and closure details
  • Detailed explanation of JavaScript closure issues
  • 9 usage scenarios of js closures
  • Use cases for JavaScript closures
  • JavaScript Advanced Closures Explained

<<:  How to solve the synchronization delay caused by MySQL DDL

>>:  Web Design Tutorial (7): Improving Web Design Efficiency

Recommend

Kill a bunch of MySQL databases with just a shell script like this (recommended)

I was woken up by a phone call early in the morni...

How to convert rows to columns in MySQL

MySQL row to column operation The so-called row-t...

Example of making a butterfly flapping its wings with pure CSS3

Pure CSS3 makes a butterfly flapping its wings, s...

HTML implements a fixed floating semi-transparent search box on mobile

Question. In the mobile shopping mall system, we ...

A brief discussion on the definition and precautions of H tags

Judging from the results, there is no fixed patte...

Complete steps for deploying confluence with docker

Confluence is paid, but it can be cracked for use...

HTML table_Powernode Java Academy

To draw a table in HTML, use the table tag tr me...

Example code of the spread operator and its application in JavaScript

The spread operator allows an expression to be ex...

Essential bonus items for optimizing and packaging the front end of Vue projects

Table of contents Preface 1. Routing lazy loading...

Multiple solutions for cross-domain reasons in web development

Table of contents Cross-domain reasons JSONP Ngin...

Specific example of MySQL multi-table query

1. Use the SELECT clause to query multiple tables...

Implementation of CSS circular hollowing (coupon background image)

This article mainly introduces CSS circular hollo...