What is the closure in JS? For the first contact with the concept of closure of friends, I believe that a lot of friends will be a little less understanding, the next article will give you a say
How to understand the JS closure。
Closure (closure) is a difficult point in JS, but also its characteristics, many advanced applications rely on closures to achieve. So let's look at the concept of JS closures first.
What is a closure?
According to the official explanation, the so-called closure refers to an expression (usually a function) that has many variables and an environment that binds them, and therefore these variables are also part of the expression.
Look at this concept alone, I believe a lot of friends will feel difficult to understand, after all, this statement is too "official", so, let's say a way to understand the JS closure. So that you can more clearly understand what JS closures are.
Understanding of JS Closures
Let's first look at an example:
def foo () { var a = 1; def bar () { A = a + 1; alert (a); } return bar;} var closure = foo (); This time the bar () is returned and the variable on its package a;var closure2 = foo (); This also generates another closure (instance) closure (); 2closure2 (); 2, bind another copy of the variable Aclosure (); 3
From this example we can see:
For the normal Foo () method, the existence of the variable a inside it should disappear after the Foo () method has finished executing, but the Foo () method returns a new square bar (), which accesses the variable A of the Foo () method (JavaScript passes the S Cope Chain access to the Parent property), and the presence of the method bar () prolongs the existence of variable A, similar to closing the variable A at its own scope, as long as the method bar () is not invalidated, the variable A is always accompanied by the method bar (), and the variable A and Method bar () of such a form of existence is called closure.
From the above example, can we re-summarize the understanding of JS closures?
A closure is a lexical scope created by a function that can be used freely outside the lexical environment after the variables created are referenced.
Closures are often used to create internal variables so that they cannot be arbitrarily modified externally and can be manipulated by a specified function interface.
OK, now the closure of JS has a clearer understanding, if still do not understand, you can go to the PHP Chinese web JavaScript Video tutorial section to learn.