Home  >  Article  >  Web Front-end  >  Analysis of closure principles in JavaScript_javascript skills

Analysis of closure principles in JavaScript_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:32:551088browse

Let's look at a definition:
Closure
The so-called "closure" refers to an expression (usually a function) that has many variables and an environment bound to these variables, so these variables are also the expression part of the formula.
This shows that closure in JavaScript is a function that contains context. In other words, the basis of this function is the environment in which it is located. This cannot be surpassed. Is it a bit familiar to linear algebra? What about the feeling?
Looking at it from another perspective, the function of closure is to achieve OO. In JavaScript, there are no public, private, and protect attribute marks like C, so it is difficult to establish a class. "A class is data with behavior, and a closure is behavior with data." In JavaScript, we replace the definition of a class with the definition of a function, and replace the setter/getter method with a closure. Please look at a piece of livecode:

Copy code The code is as follows:

function f1(){
var n=1;
function getter(){
alert(n);
}
return getter; and function getter form a typical closure. The function that is finally returned, the "behavior" just mentioned, is actually intended to get the value of n, so closure is a behavior with data.
In addition, I think what Ruan Yifeng said about closure is also very concise: "My understanding is that a closure is a function that can read the internal variables of other functions."
Another more academic explanation:

http://demo.jb51.net/js/javascript_bibao/index.htm

I hope you can really understand closure from an academic definition, because all definitions of closure Interpretation and simplification are both partial interpretations of JavaScript.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn