What is a closure packageClosures are blocks of code that can contain variables that are free (not bound to specific objects), that are not defined within this block of code or in any global context, but are defined in the context in which the code block is defined (local variables). The word "closure" derives from the combination of the following: the code block to be executed (since free variables are included in the code block, these free variables and the objects they refer to are not freed) and the computing Environment (scope) that provides the binding for free variables. In Scala, Scheme, Common Lisp, Smalltalk, Groovy, JavaScript, Ruby, Python, Lua, objective C and Java (JAVA8 and above) can find different levels of support for closures.
in the field of programming we can say in layman's terms: A child function can use a local variable in the parent function, which is called a closure! The
application of closures in JavaScriptThe "official" explanation is that the so-called "closure" refers to an expression (usually a function) that has many variables and an environment in which these variables are bound, and therefore these variables are also part of the expression. It is believed that very few people can read this sentence directly because he describes it as too academic. I want to use how to create a closing package in JavaScript to tell you what a closure is, because skipping the closure is a straightforward way to understand the definition of closures. Look at the following paragraph .
function A () { var i=0; function B () { Console.log (+ +i) ; } return b;} var c=A (); C ();
This code has two features: 1, function B is nested inside function A, 2, function a returns function B. So after executing var c=a (), the variable C actually points to function B, and then C () outputs the value (first 1). This code actually creates a closure, why? Because the variable C outside of function A refers to function B in function A, it says: When function A's internal function B is referenced by a variable outside of function A, a closure is created.
closures have many uses in JavaScriptSimulating private variablesThe code is as follows
function Counter (start) { var count = start; return { increment:function() { count+ +; }, get:function() { return count; }}} var foo = Counter (4); Foo.increment (); Foo.get (); // 5
Save state
Learn closure notes