Just this time, I'll fix the closure for you. I see!

Environment and scope of function

Understanding what is context and scope

Environment, taking our life as an example, the environment is like our surrounding facilities, schools, supermarkets, pharmacies, parks, etc. various facilities constitute our living environment.
Scope, as if these peripheral facilities can only serve the surrounding residents. It is impossible to say that people come all the way to the supermarket to buy a bottle of water and then go back all the way. Therefore, scope refers to the service scope of these facilities.

Having finished the chestnuts of life, go back to the code. Environment can be understood as some variables (data and memory) defined by us, and scope refers to the scope of these variables.

		let person = 'Peng Yuyan';
        // console.log(age);  // age is not defined
        console.log(person); // Peng Yuyan

        function func() {
            let age = 18;
            console.log(age); // 18
            console.log(person); // Peng Yuyan
        }
        func();

In the above code, person is like a supermarket, and age can be understood as my home. I can go to the supermarket and access the person variable of the supermarket, but the supermarket can't access my home and can't access the age variable of my home. The defined person and age variables are equivalent to the environment. The environment of the person variable can be scoped globally, while the age variable can only act inside the function and cannot be accessed externally.

If we go further, define another function in the function:
At this time, a dairy environment is defined. The scope is compared to my room. Only I can read the diary of my room. No one else in my family can read it, and people in the supermarket can't read it. Therefore, the scope of dairy is limited to the fn function.

		let person = 'Peng Yuyan';
        // console.log(age); // age is not defined
        // console.log(dairy); // dairy is not defined

        function func() {
            let age = 18;
            // console.log(dairy); // dairy is not defined

            function fn() {
                let dairy = 'diary'
                console.log(person); // Peng Yuyan
                console.log(age); // 18
                console.log(dairy); // diary
            }
        }
        func();

About the life cycle of the environment

We have compared the environment to facilities. The existence of surrounding public facilities is because someone is using them. If people in an area leave, these facilities have no meaning to exist, and they will face demolition. Therefore, when a piece of data (environment) is used up and no longer used, its life cycle is over and will be recycled.

Let's take chestnuts as an example. We hope to realize an accumulation function

		function func() {
            let n = 1;

            function sum() {
                console.log(`Today is study JS The first ${++n}day`);
            }
            sum();
        }
        func(); // Today is the second day of learning JS
        func(); // Today is the second day of learning JS
        func(); // Today is the second day of learning JS

We know that the statement of the function will disappear after being executed from top to bottom, and will be cleared. If it is called repeatedly, it will only be re executed.

So how can an environment not be cleaned up? If someone uses it, it won't be cleaned up.

Therefore, we might as well let this function be used all the time and assign the function to fn. In fact, we assign the address of the function to fn. Therefore, when calling fn for the first time, n=2, then n saved in this address is 2. Therefore, when calling fn again, add 1 on the basis of n=2 and accumulate in turn.

		function func() {
            let n = 1;

            return function() {
                console.log(`Today is study JS The first ${++n}day`);
            }
        }
        let fn = func();
        fn(); // Today is the second day of learning JS
        fn(); // Today is the third day of learning JS
        fn(); // Today is the fourth day of learning JS
        fn(); // Today is the fifth day of learning JS

 
 
 

closure

What is a closure?

In fact, when the environment and scope are mentioned above, the examples of nested functions are closures. So what is a closure? A closure is a function that can access the parent scope. In other words, in my own room, I can visit my home and various facilities outside. This is closure.

Closure code instance

Give a few examples to deepen your impression:

		function init() {
            let user = 'Peng Yuyan';
			// func function defines the word in init function
            function func() {
            	// There is no local variable defined in func function, but the variable of external function can be accessed
                console.log(user); // Peng Yuyan
            }
            func();
        };
        init();

Obtain the data of the corresponding interval:

		let arr = [98, 1, 123, 41, 54, 7, 41, 92, 72, 95]

        function between(start, end) {
            return arr
            	// The arrow function in the filter parameter is a sub function of the between function
            	// The child function can access the start and end variables of the parent function
                .filter(value => value >= start && value <= end)
                // Sort the filtered array
                .sort((a, b) => a - b)
        }
        console.log(between(50, 100)); // [54, 72, 92, 95, 98]

Sort by field:

		let array = [{
            name: 'Zhang San',
            score: 88,
            age: 19
        }, {
            name: 'Li Si',
            score: 78,
            age: 20
        }, {
            name: 'Wang Wu',
            score: 82,
            age: 27
        }, {
            name: 'Liu Liu',
            score: 59,
            age: 22
        }, {
            name: 'Lin Qi',
            score: 42,
            age: 52
        }, {
            name: 'Zhao Ba',
            score: 67,
            age: 25
        }, {
            name: 'Zheng Jiu',
            score: 32,
            age: 34
        }];
		
		
        function order(field) {
        	// The order function has a sort sort function inside
        	// The sorting function can access the field variable of order
            return array.sort((a, b) => a[field] > b[field] ? 1 : -1)
        }
        let fn = order('score');
        console.log(fn);

Adjust font size:

		<button>25px</button>
	    <button>40px</button>
	    <p>I'm just a p</p>


        let btns = document.querySelectorAll("button");
        let p = document.querySelector("p");
        btns.forEach((item) => {
        	// The internal function of the forEach method when the event is clicked
            item.addEventListener("click", () => {
            	// Click the variable whose function does not declare item, but you can use the item of the parent function
                p.style.fontSize = item.innerHTML;
            });
        });

When you click the 25px button, the font size changes to 25px

When you click the 40px button, the font size changes to 40px

I spent a lot of time explaining the environment and scope in order to better understand what closures are. I hope this article will be helpful to you. If there are any errors, please correct them. Thank you!

Keywords: Javascript Front-end ECMAScript memory management

Added by norbie on Wed, 02 Feb 2022 05:25:55 +0200