Introduction to closures
In JavaScript, redeclaring the same variable can lead to variable conflicts. In such cases, closures can be used to create independent execution environments.
In JavaScript, a closure refers to a closed execution environment. It means a function can remember and access the scope in which it was created, even if it is executed outside its original scope. In other words, an inner function has access to variables in the scope of another outer function. Closures are typically created by nested functions , where one function defines another function inside it. The outer function can return the value of the inner function, and the inner function can access variables of the outer function.
The syntax is as follows:
function f2() {
var user = 'Guest';
return function () {
console.log("hello2" + user);
}
}
var bibao2 = f2();
bibao2();
Define a function f1, define a variable user in the local scope of function f1, and then define an anonymous function as the return value of function f1. The anonymous function can access user, that is, the inner function can access the variable in the scope of the outer function.
// local variable
function f1() {
var user = 'Guest';
function foo() {
console.log("hello" + user);
}
// Using this function as the return value of f1, calling f1 can obtain foo
return foo;
}
// The closed environment formed by f1 is called a closure
var bibao1 = f1();
bibao1();
Change f1 to use the form of directly returning the function `return function()`.
function f2() {
var user = 'Guest';
return function () {
console.log("hello2" + user);
}
}
var bibao2 = f2();
bibao2();
Define an add() function and a local variable num. Write an inner function inside the function as the return value. If you don’t write this inner function, the value you see each time will only be 0 (the initial value).
The `add()` function returns a closure that can access and modify the variable `num` within the scope of the `add()` function. Each time this closure is called, it increments the value of `num` and prints it.
function add() {
var num = 0;
return function () {
num++;
console.log('Number:', num);
}
}
Create two instances of closures, bibao3 and bibao4. Each time the add function is called, each closure will create a new num variable (equivalent to allocating new memory space). bibao3 and bibao4 are directly independent of each other.
Since calling a function is done in the form of function name(), why can’t we directly access the closure using function name()()?
The role of closure
Closures can preserve the state of variables.
When a closure is created, a new memory space is created, and each closure allocates its own independent memory space. Variables within a closure can remember the current state, and when the closure is used again, it will retain the previous state.
In the previous example, each time bibao3() or bibao4() is called, it increments by the value of the previous call.
Closures allow variables to be made private.
Each time a new closure is created, its own independent memory space is allocated, and the variables of the closure are all private.
In the previous example, the num value of bibao3() and bibao4() is different each time.
Disadvantages of closures
While closures offer powerful encapsulation and data protection capabilities in JavaScript, they also have some drawbacks. First, because closures can capture and hold variables in their creation scope for an extended period, this can lead to increased memory usage, especially with a large number of closures created, potentially causing memory leaks. Second, closures can create untraceable circular references, hindering the efficiency of JavaScript’s garbage collection mechanism and thus impacting program performance. Furthermore, improper use of closures can increase code complexity, making it more difficult to understand and maintain. Therefore, developers need to use closures cautiously, ensuring that references are released promptly when no longer needed to avoid unnecessary memory consumption, and organizing code logically to improve readability and maintainability.