Let's look at a definition:
Closure
The term "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.
This shows that the closure in JavaScript is a function that contains the context, that is, the function of the role is based on its environment, which is not beyond, and linear algebra is not a little déjà vu it?
In other words, the closure is designed to achieve OO. In JavaScript, there is no public, private, protect attribute identity like C + +, and it is difficult to build a class. "Class is data with behavior, and closure is behavior with data", in JavaScript we use function definitions instead of class definitions, and closures instead of setter/getter methods. Take a look at a livecode:
Copy Code code as follows:
Function F1 () {
var n=1;
Function getter () {
alert (n);
}
return getter;
}
The Declaration and function getter of n above form a typical closure. The final return function, the "behavior" just described, is designed to get the value of N, so closures are the behavior of data.
In addition, I think Nanyi's closure is also very concise: "My understanding is that closures are functions that can read internal variables of other functions." ”
Another more scholarly explanation:
Http://demo.jb51.net/js/javascript_bibao/index.htm
I hope that you can really understand the closure in terms of the academic definition, because all interpretation and simplification of the definition of closures is a one-sided interpretation of JavaScript.