Js closure problem

I would like to ask the meaning of the existence of closures. If you want to use the methods and variables of the outer function, just return the method and variable of the outer function directly, why return the inner function and then reference it from the inner function?

Mar.28,2021

you put the outer variable retrun out, and the variable is recycled after your function is run. If you use the reference in the inner function, it will not be recycled, because the reference is there. All right, take Liezi for example, there is a department tree with a large amount of data, and this tree will not change basically. At this time, I will use a closure to reference it. Next time I call it, it is still there, directly take the memory, how nice, how happy, no need to request background, no need to calculate. But remember not to clear to prevent memory overflow.


The advantage of

closures is to avoid global pollution, and the disadvantage is to cause memory leaks. The trade-off between the two needs to be weighed by yourself. It is not necessary to use closures

.

you are talking about putting the outer function method and variable return out, so where is the return? No, return went to the global, since a large number of variables are declared in the global, which may cause global pollution, moreover, why does the return go out, isn't it more direct for you to define it directly in the global?

if you want to use it this way, you can declare an empty object let myData = Object.creat (null) , and then store all your data in this myData, where access is here, and avoid global pollution

.
Menu