There are four ways to answer this question:
- What is a closure
- What problems do closures solve
- Application scenarios for closures
- Disadvantages of closures
What is a closure
A function that accesses a variable in the scope of another function.
Then explain this sentence, in JS function can form a scope, completes the scope will be destroyed, but the closure is just not the same, because the closure is a function of internal son function, the inner function can access the superior scope, because there are a variable reference function scope, therefore completes not immediately destroyed.
What problems do closures solve
- You can read variables inside a function
- Keep these variables in memory at all times and not cleared after function calls.
let bar = function () {
let local = 'Local variable'
return function () {
return local
}
}
let baz = bar()
console.log(baz())
console.log(baz())
Copy the code
Normally, local variables are destroyed along with the scope after executing bar, but this returns an anonymous function that has access to the local variable in the parent scope. The scope of bar does not destroy variables if it finds references to them. Although local cannot be accessed directly from an external scope, it can be accessed by simply iterating through the intermediate function. Then you can just call the baz function to get the local variable, no matter how many times you do it. The problem is that once a variable references the intermediate function, the intermediate function will not be freed, and the original scope will not be freed.
Application scenarios for closures
The state of a variable is preserved by suppressing it with a closure
function addCounter() {
let counter = 0
const myFunction = function () {
counter = counter + 1
return counter
}
return myFunction
}
const increment = addCounter()
const c1 = increment()
const c2 = increment()
const c3 = increment()
console.log('increment:', c1, c2, c3);
// increment: 1 2 3
Copy the code
Increment (myFunction); increment (1); increment (2); increment (3); This proves that the local variable counter in the function addCounter is kept in memory and is not automatically cleared when addCounter is called. The sum of numbers is achieved by suppressing variables.
F (1)(2)(3) 1+2+3
// Implement method 1, use closure to suppress variables, save parameters, when the parameters reach a certain number of summation operation
const add = (function (length) {
let allArgs = [];
function _add (. args) {
allArgs = [...allArgs, ...args];
if (allArgs.length >= length) {
let res = allArgs.reduce((prev, cur) = > prev + cur, 0);
allArgs.length = 0
return res;
} else {
return_add; }}return _add
})(3)
Copy the code
Similarly, implement (10).add(10).add(1)
Number.prototype.add = function (a) {
let value = this.valueOf()
function next(num) {
value = value + num
return value
}
let result = next(a)
return result
}
let a = (10).add(10).add(1)
console.log(a) / / 21
Copy the code
Disadvantages of closures
Because closures carry the scope of the function that contains them, they take up more memory than other functions. Overuse of closures can lead to excessive memory usage, and we advise readers to consider using closures only when absolutely necessary. While optimized JavaScript engines like V8 try to reclaim memory used by closures, use closures with caution.