JavaScript Closures Explained

JavaScript Closures Explained

1. What is a closure?

Closure: The combination of a function and the state of the environment in which the function is declared.
That is to say, a function can access the variables of the environment in which it is defined even if it is called outside of the environment in which it is defined.

So using closures, you can associate data with functions that operate on that data.

For example:

function foo() {
	let a = 1;
	return function() {
		console.log(a);
	}
}
let foo1 = foo();
foo1() // Output 1

This is an example of a closure. In foo, because a function is returned, this function has a closure covering the internal scope of foo, that is, a, so that a always survives and will not be recycled when foo ends.

2. The role of closures

2.1) Memory

What is the memory property of closures?

When a closure is generated, the state of the environment in which the function is located will always remain in the memory and will not be reclaimed by the garbage collection mechanism after the outer function call ends.

For example:

function foo() {
    let a = 0;
    return function() {
        a++;
        console.log(a);
    }
}
let foo1 = foo();
let foo2 = foo();
foo1(); // 1
foo2(); // 1
foo2(); // 2
foo1(); // 2

insert image description here

Because a is part of the closure, when the closure is generated, the environment state of a will be kept in the memory and will not be cleared after the outer function call ends. Therefore, as foo1 is used, the value of a in the memory will increase by 1.
Then the closures produced by foo1 and foo2 are two independent closures that do not affect each other. So when foo2 is called for the second time, it adds 1 to the result of its first call.

2.2) Simulating private variables

Ensure that a variable can only be operated on by specified operations.

For example :

function foo() {
	let A = 0;
	return {
	    getA : function() {
	        return A;
	    }, 
	    add : function() {
	        A++;
	    },
	    del : function() {
	        A --;
	    }
	}
}
let foo1 = foo();
console.log(foo1.getA()); // 0
foo1.add();
console.log(foo1.getA()); // 1
foo1.del();
console.log(foo1.getA()); // 0

insert image description here

Through closure, it is ensured that A can only be subjected to the specified addition and subtraction operations.

3. Notes on closures

Closures should not be abused, otherwise they may cause performance problems on the web page due to excessive memory usage, and may even cause memory leaks.

Summarize

This article ends here. I hope it can be helpful to you. I also hope you can pay more attention to more content on 123WORDPRESS.COM!

You may also be interested in:
  • Let's talk in detail about the role of closures in JS
  • Detailed explanation of the principle and function of JavaScript closure
  • JavaScript Advanced Closures Explained
  • JavaScript closure details
  • Let's learn what javascript closures are

<<:  Illustration of properties such as offsetWidth, clientWidth, scrollWidth, scrollTop, scrollLeft, etc.

>>:  Summary of Docker Consul container service updates and issues found

Recommend

IIS7 IIS8 reverse proxy rule writing, installation and configuration method

Purpose: Treat Station A as the secondary directo...

Enabling and configuring MySQL slow query log

Introduction MySQL slow query log is an important...

Detailed explanation of crontab scheduled execution command under Linux

In LINUX, periodic tasks are usually handled by t...

Detailed description of component-based front-end development process

Background <br />Students who work on the fr...

Basic operation tutorial of files and permissions in centos

Preface Before we begin, we should briefly unders...

How to set static IP for Ubuntu 18.04 Server

1. Background Netplan is a new command-line netwo...

Summary of MySQL ALTER command knowledge points

When we need to change the table name or modify t...

Explanation of the process of docker packaging node project

As a backend programmer, sometimes I have to tink...

An Incomplete Guide to JavaScript Toolchain

Table of contents Overview Static type checking C...

InnoDB type MySql restore table structure and data

Prerequisite: Save the .frm and .ibd files that n...

Detailed explanation of how to use zabbix to monitor oracle database

1. Overview Zabbix is ​​a very powerful and most ...

Vue uses canvas to realize image compression upload

This article shares the specific code of Vue usin...

Summarize the common application problems of XHTML code

Over a period of time, I found that many people d...

CSS realizes the scene analysis of semi-transparent border and multiple border

Scenario 1: To achieve a semi-transparent border:...