Offer to come, dig friends take it! I am participating in the 2022 Spring Recruit Punch card activity. Click here for details.
⭐ ⭐
A:
Immediate-execute functions are often used in closures to make the implementation of closures a little less code.
Before reading this article, it’s best to understand what this article is about:
Tell us what you understand about closures
Execute function concepts immediately
The immediate execution of a function is characterized by:
- Declare an anonymous function
- Call this anonymous function immediately
- Destroy the anonymous function
(function () {
let name = '阿林'
console.log(name)
})()
Copy the code
Is equivalent to
function fn() {
let name = '阿林'
console.log(name)
}
fn()
Copy the code
As you can see, executing a function immediately means wrapping a piece of code in an anonymous function and immediately executing the code logic, which is the same as declaring a function, writing the code logic into the function, and then calling the function.
Functions have two main functions:
- Encapsulate code and reuse it
- There are function scopes that isolate variables
Obviously, the immediate function cannot be reused, so the immediate function does:
- Simplify code, no need to encapsulate, then call, do not have a function name
- There are function scopes that isolate variables
And the closure
Many articles on the web often mix the concepts of immediate functions and closures. Indeed, the immediate functions and closures are often used together, which can lead to misunderstandings.
In fact, the immediate effect of the function is to make the implementation of the closure less code, as in this example:
// Do not execute the function immediately
function sayName () {
const name = '阿林'
return function () {
console.log(name)
}
}
const fn = sayName()
fn() // output 'alim'
Copy the code
// Use the immediate execution function
const fn = (function () { // Write an anonymous function without naming it
const name = '阿林'
return function () {
console.log(name)
}
})()
fn() // output 'alim'
Copy the code
Closures can be implemented with or without immediate execution of the function, hiding the variable name from global access.
At the end
If my article is helpful to you, your 👍 is my biggest support ^_^
You can also follow the front End Daily Question column in case you lose contact
I’m Allyn, export insight technology, goodbye!
The last:
What is the execution stack in “Front-end Daily Question (29)” JS?
Next up:
How to design a cache module with closures?