Home > Article > Web Front-end > What is the role of JS closures?
The function of JS closure is to prevent Javascript's garbage collection mechanism from reclaiming the resources occupied by A after A is executed and returned, because the execution of A's internal function B needs to depend on the variables in A. If closures are not used, the variables that function B depends on for execution will cause global pollution.
The essence of closure
The set S is a closed set if and only if Cl(S)= S (cl here is closure, closure). In particular, the closure of the empty set is the empty set, and the closure of X is X. The closure of the intersection of sets is always a subset (not necessarily a proper subset) of the intersection of the closure of sets. The closure of the union of finitely many sets is equal to the union of the closures of these sets; the union of zero sets is the empty set, so this proposition includes the previous special case of the closure of the empty set. The closure of the union of infinite sets is not necessarily equal to the union of the closures of these sets, but the former must be the parent set of the latter.
If A is a subspace of X containing S, then the closure of S calculated in A is equal to the closure calculated of A and S in )) intersection. In particular, S is dense in A if and only if A is a subset of Cl_X(S).
Closure example
Simulating private variables:
function Counter(start){ var count = start; return{ increment:function(){ count++; }, get:function(){ return count; } } } var foo = Counter(4); foo.increment(); foo.get();// 5
Here, the Counter function returns two closures, the function increment and the function get. Both functions maintain a reference to the outer scope Counter, so they can always access the variable count defined in this scope.
Recommended tutorial: "JavaScript"
The above is the detailed content of What is the role of JS closures?. For more information, please follow other related articles on the PHP Chinese website!