This is the 10th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021
In the previous article, we learned a few amazing “bugs” in JavaScript that aren’t perfect but don’t affect how it works:
The last article covered optional arguments to functions. This article continues with JavaScript function closures
JavaScript functions – closures
A closure is a function nested within a function.
Closure concept
A closure is a function that reads the internal variables of other functions (this one).
The function B- closure is inside A function defined by A variable called variable, so that the function B- closure can fetch the value of the variable. Closures allow you to access the scope of an outer function in an inner function. Look at the below MDN – closure | closure:
MDN | a function and state of the surrounding (lexical environment, lexical environment) a reference to the bundled together surrounded by reference (or function), this combination is a closure (closure).
In JavaScript, whenever a function is created, the closure is created at the same time the function is created.
What does that mean? Why create a function that also creates a closure? Take a look at the code implementation:
(Chinese code programming style :–)
functionfunctionA() {
// variable is A local variable created by function A
var variable = 'Variables inside function A, outside function B'
functionfunctionB() {
// Function B() is an inner function of function A, which is A closure
alert(variable) // Use a variable declared in the parent function} function B()} function A()Copy the code
To understand closures, you need to understand the lexical scope of nested functions:
// Be careful to distinguish the positions of the two variables
let scope = 'global scope' // Global variables
function checkScope(){
let scope = 'inner scope' // Internal variable (local variable)
function fn(){
return scope // Returns the value of the current scope via a closure function
}
return fn()
}
checkScope() // return to inner scope
Copy the code
Question to ponder: How do you understand closures
An extended understanding of closures is updated below
Closures are useful, and in practice we may use them without realizing it:
For example, it is often used in development to assign an external this value to a variable that the closure will use for inheritance: give nested functions access to the external this value (isn’t that common).
const self = this;
Copy the code
Ps: Creating a function creates a closure…
- Recursion: function calls itself
- Higher-order functions: a function that operates by taking other functions as arguments or by returning other functions
- .