closure

What is the sum of a closure “function” and “variables accessible within the function” (also known as the environment), that is a closure

The sum of the variables that can be accessed inside the function and the variables that can be accessed inside the function, Var local = "variable" function foo(){console.log(local)} the above three lines of code are in an immediate function. So in three lines of code, we have a local variable, and we have a function foo, which accesses the local variable.Copy the code

Closure nested functions

Function foo(){var local = 1 function bar(){local++ return local} return bar} var func = foo() func() local variables and bar The function forms a Closure. Why do functions cover functions? We need local variables so we put local in the function. If we don't put local in the function,local becomes a global variable and we defeat the purpose of the closure. Why return bar? If you don't return, you can't use the closure Retuen Bar is as long as the outside can access the bar function, so return bar is just for the bar to be used, it has nothing to do with the closure.Copy the code

The role of closures

Closures are often used to "indirectly access a variable." In other words, "hide a variable." Let's say we're making a game, and we're writing code about how many lives we have left. Instead of closures, you could just use a global variable: window.lives = 30 // And thirty lives. What if I accidentally change this value to negative 1? So we can't give someone "direct access" to this variable. What to do? Use local variables. But with local variables others can not access, how to do? Expose an accessor (function) that others can "indirectly access." ! Function (){window.addlife = function(){lives += 1}// window.lostlife = function(){lives -= 1}// closure} then in other JS files, you can use window. Bonus a life () to gain a life, use window.die a life () to lose a life.Copy the code