Let's look at a definition:
Closure
A closure refers to an expression (usually a function) with many variables and an environment bound to these variables. Therefore, these variables are part of the expression.
This shows that the closure in Javascript contains the context function. That is to say, the function is based on its environment, which cannot be exceeded, does it seem familiar to linear algebra?
From another perspective, closures are used to implement oo. In JavaScript, there are no public, private, and protect attribute identifiers like C ++. It is difficult to establish a class. "A class is a data with behaviors, while a closure is a behavior with data". In JavaScript, we use the function definition to replace the class definition, and use the closure to replace the setter/getter method. Please refer to the livecode section:
CopyCodeThe Code is as follows: function F1 (){
VaR n = 1;
Function getter (){
Alert (N );
}
Return getter;
}
The n declaration and the getter function constitute a typical closure. The final returned function, that is, the "action" just mentioned, aims to get the value of N, so closure is the act of carrying data.
In addition, I think the closure mentioned by Ruan Yifeng is also very concise: "In my understanding, the closure is a function that can read internal variables of other functions ."
Another more academic explanation:
Http://demo.jb51.net/js/javascript_bibao/index.htm
I hope that you can understand the closure from an academic perspective, because all interpretations and simplification of the closure definition are one-sided interpretations of JavaScript.