Before Reading

You must understand function scope, if not you can search this site

What exactly is a closure, why always neng unclear, this time I let you completely neng clear

Let’s start with the simplest code

let i = 0;
function f() {
	i++;
	return i;
}
console.log(f());/ / 1
console.log(f());/ / 2
console.log(f());/ / 3
console.log(f());/ / 4
console.log(f());/ / 5
Copy the code

Ok, you can see that function F refers to a variable I. Think about what happens every time you call function F.

What if I wrap this code around functions? To avoid confusion, let’s take it one step at a time

1. Wrap the function and return

function c(){
	let i = 0;
	return function f() {
		i++;
		returni; }}Copy the code

2. Cancel the named function and return the anonymous function

function c(){
	let i = 0;
	return function () {
		i++;
		returni; }}Copy the code

3. Receive the return value and execute the code

let f = c();
Copy the code

Take a look at the final code

function c(){
	let i = 0;
	return function () {
		i++;
		returni; }}let f = c();
console.log(f());/ / 1
console.log(f());/ / 2
console.log(f());/ / 3
console.log(f());/ / 4
console.log(f());/ / 5
Copy the code

What has changed since the original code?

1. The variable I is inside the function. You can’t access it outside the function

2. However, you can access this variable in the return value of function C, the internal anonymous function

3. Function C is not destroyed after execution because its internal variable I is referenced by f, so the value of I changes and is saved every time f() is executed

In fact, a closure is a representation of the scoped nature of a function; every function is called a closure when executed, but some functions are not destroyed.

Finally: Forget closures and remember function scopes