Home > Article > Web Front-end > Detailed explanation of the use of js closure_Basic knowledge
Let’s take a look at the uses of closures. In fact, by using closures, we can do a lot of things. For example, it can simulate the object-oriented coding style; express the code more elegantly and concisely; and improve the execution efficiency of the code in some aspects.
1 Anonymous self-executing function
We know all variables. If you do not add the var keyword, they will be added to the properties of the global object by default. There are many disadvantages to adding such temporary variables to the global object,
For example: other functions may misuse these variables; causing the global object to be too large and affecting access speed (because the value of the variable needs to be traversed from the prototype chain).
In addition to using the var keyword every time a variable is used, we often encounter such a situation in actual situations, that is, some functions only need to be executed once, and their internal variables do not need to be maintained.
For example, for UI initialization, we can use closures:
2 cache
Then we need to store the calculated value. When calling this function, first search it in the cache. If it cannot be found, then calculate it,
Then update the cache and return the value. If found, just return the found value directly. Closures do exactly this because they do not release external references,
Thus the value inside the function can be preserved.
The code is as follows:
The code is as follows:
It can be seen from this code that both john and jack can be called instances of the Person class, because the two instances have independent access to the name member and do not affect each other.
The above is the function of js closure. It is very simple and easy to understand. I hope it will be helpful to my friends