Detailed explanation and examples of JS closures:
Recently, I have learned the basic knowledge of JS and learned the knowledge points of closures. I have a lot of doubts. I have been reading the knowledge related to closures for a while. I have a little more in-depth understanding. Let me talk about my understanding below.
function fn(){ var a = 0; return function (){ return ++a; } }
As shown above, the first return above returns is a closure, so essentially the closure is a function. So what's the use of returning this function?
That's because this function can call the variable a outside it. In fact, return returns the variable + a
So, let's use this closure to do something
We might as well create a variable var f = fn(); If(f) You will know at once that this f is the entire function body of return, that is, function () { return ++a;}
Then, when we execute f(), it is equivalent to executing the function function. If we execute f() multiple times, the returned a value will be superimposed.
But if we create another variable var f2 = fn(); If we run f2(), we will find that the value of a has been reset. It will start from 0 again. Why is this?
In fact, we can understand it in this way. First of all, the closure is an anonymous function. Now that we assign it to a variable, it has a name, and then it has a place to store it after each execution. However, the places where each variable is stored are different. They are not related to each other, so they are independent individuals, so the value of a is different. Just think that different functions have been executed, but the function body is exactly the same.
So, what are the application scenarios of our closures? I had been thinking before that because I was very humble, I didn’t use many closures to write code. But today when I was looking at the front-end design pattern, I saw the singleton pattern and thought about it. Isn’t this a good application scenario for closures?
For example, my current requirement is like this. Sometimes I need a mask layer in a web page. When I call it, I will create one, but you can't create it every time you call it, so if it exists, use the previous one, and if it does not exist, create a new one, but at the same time, it is possible that I will never need this mask layer, so I may never need to create it.
This is a very typical singleton pattern scenario.
So how can we achieve it?
function fn() { var a; return function() { return a || (a = (('div'))); } }; var f = fn(); f();
It's very simple, just change the previous code slightly. The relevant understanding is also clearly stated above, you can see it carefully.
Okay, now I have a little deeper understanding of closures. Next, we will continue to go deeper slowly, and the blogger will update it in time.
Thank you for reading, I hope it can help you. Thank you for your support for this site!