SoFunction
Updated on 2025-03-01

Analysis of closure principle in JavaScript

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 part of the expression.
This shows that the closure in JavaScript is a function that contains context. In other words, the basis of this function is the environment it is in, which cannot be surpassed. Does it feel a bit familiar to linear algebra?
From another perspective, the function of closure is to realize OO. In JavaScript, there are no public, private, and protect attribute identifiers like C++, so it is difficult to establish a class. "Class is data with behavior, while closures are behavior with data." In JavaScript, we use function definitions instead of class definitions and closures instead of setter/getter method. Please see a livecode:
Copy the codeThe code is as follows:

function f1(){
var n=1;
function getter(){
alert(n);
}
return getter;
}

The declaration of n and function getter in the above form a typical closure. The final returned function, which is the "behavior" just mentioned, is actually aimed at getting the value of n, so the closure is the behavior with data.
In addition, I think the closure that Ruan Yifeng mentioned is also very concise: "My understanding is that closures are functions that can read internal variables of other functions."
Another more academic explanation:
http://demo./js/javascript_bibao/
I hope you can truly understand closures from an academic definition, because all interpretations and simplifications of closure definitions are one-sided interpretations of JavaScript.