This article will explore in-depth three crucial concepts in modern JavaScript development: closures, callback functions, and immediate execution function expressions (IIFE). We have learned in detail about variable scope and enhancement, and now let's complete our exploration journey.
Core points
Closing
In JavaScript, a closure is any function that retains references to its parent scope variable, even if the parent function has returned .
Actually, any function can be considered a closure, because as we learned in the variable scope section of the first part of this tutorial, a function can be referenced or accessed:
Point 1: You can refer to variables defined outside the current function.
In this code example, the
function refers to thefunction setLocation(city) { var country = "France"; function printLocation() { console.log("You are in " + city + ", " + country); } printLocation(); } setLocation("Paris"); // 输出:You are in Paris, France
parameter of the enclosed (parent) printLocation()
function. As a result, when setLocation()
is called, country
successfully outputs "You are in Paris, France" using the former variables and parameters. city
setLocation()
Point 2: printLocation()
Inner functions can refer to variables defined in external functions even after the external function returns.
function setLocation(city) { var country = "France"; function printLocation() { console.log("You are in " + city + ", " + country); } printLocation(); } setLocation("Paris"); // 输出:You are in Paris, France
This is almost the same as the first example, except this time printLocation()
returns in the outside the setLocation()
function, rather than calling immediately. Therefore, the value of currentLocation
is the internal printLocation()
function.
If we remind like this currentLocation
– alert(currentLocation);
– we will get the following output:
function setLocation(city) { var country = "France"; function printLocation() { console.log("You are in " + city + ", " + country); } return printLocation; } var currentLocation = setLocation("Paris"); currentLocation(); // 输出:You are in Paris, France
As we have seen, printLocation()
is executed outside its lexical scope. setLocation()
seems to disappear, but printLocation()
can still access and "remember" its variables (country
) and parameters (city
).
The closure (inner function) is able to remember the scope around it (external function) even if it executes outside its lexical scope. So you can call it later at any time in your program.
Point 3: Inner functions store variables that are external functions by reference, rather than by values.
function printLocation () { console.log("You are in " + city + ", " + country); }
Here cityLocation()
Returns an object containing two closures—get()
and set()
—both refer to external variables city
. get()
Gets the current value of city
and set()
updates it. When the second call myLocation.get()
, it outputs an updated (current) value of city
- "Sydney" - instead of the default "Paris".
Therefore, closures can both read and update their stored variables, and these updates are visible to any closure that accesses them. This means that the closure stores a reference to its external variable instead of copying its value. This is a very important point, because not knowing this can lead to some difficult-to-find logical errors – as we will see in the "Execute Function Expressions immediately (IIFE)" section. An interesting feature of
The closure is that variables in the closure are automatically hidden. Closures store data in their enclosed variables without providing a way to access them directly. The only way to change these variables is to access them indirectly. For example, in the last code snippet, we see that we can only indirectly modify the variable by using get()
and set()
closures. city
As you can see, there is nothing mysterious or profound around the closure—just three simple points to remember.
Callback function
In JavaScript, functions are first-class citizens. One of the consequences of this fact is that functions can be passed as arguments to other functions or returned by other functions.Functions that take other functions as parameters or return functions as their results are called higher-order functions, and functions passed as parameters are called callback functions. It is called a "callback" because at some point in time, it will be "callback" by a higher-order function.
Callback functions have many daily uses. One of them is when we use the setTimeout()
and setInterval()
methods of the browser window object - these methods accept and execute the callback function:
function setLocation(city) { var country = "France"; function printLocation() { console.log("You are in " + city + ", " + country); } printLocation(); } setLocation("Paris"); // 输出:You are in Paris, France
Another example is when we attach an event listener to an element on the page. By doing this, we actually provide a pointer to the callback function, which will be called when the event occurs.
function setLocation(city) { var country = "France"; function printLocation() { console.log("You are in " + city + ", " + country); } return printLocation; } var currentLocation = setLocation("Paris"); currentLocation(); // 输出:You are in Paris, France
The easiest way to understand how higher-order functions and callback functions work is to create your own higher-order functions and callback functions. So, let's create one now:
function printLocation () { console.log("You are in " + city + ", " + country); }
Here we create a function fullName()
, which accepts three parameters - two for first and last name, and one for callback function. Then, after the console.log()
statement, we place a function call that will trigger the actual callback function—the fullName()
function defined below greeting()
. Finally, we call fullName()
where greeting()
is passed as a variable— without brackets—because we don't want it to be executed immediately, but just want to point to it for later use by fullName()
.
We are passing function definitions, not function calls. This prevents the callback function from being executed immediately, which is inconsistent with the philosophy behind the callback function. Passed as function definitions, they can be executed at any time and at any point in the containing function. Furthermore, because callback functions behave like they are actually placed inside the function, they are actually closures: they can access variables and parameters containing the function, and even access variables in the global scope.
The callback function can be an existing function (as shown in the previous example) or an anonymous function. We create an anonymous function when calling higher-order functions, as shown in the following example:
function cityLocation() { var city = "Paris"; return { get: function() { console.log(city); }, set: function(newCity) { city = newCity; } }; } var myLocation = cityLocation(); myLocation.get(); // 输出:Paris myLocation.set('Sydney'); myLocation.get(); // 输出:Sydney
Callback functions are widely used in JavaScript libraries to provide versatility and reusability. They allow easy customization and/or extension of library methods. In addition, the code is easier to maintain and is more concise and easy to read. Callback functions come in handy whenever you need to convert unnecessary duplicate code patterns into more abstract/generic functions.
Suppose we need two functions - one that prints the published article information and the other that prints the sent message information. We created them, but we noticed that part of our logic is repeated in both functions. We know that having the same piece of code in one place is unnecessary and difficult to maintain. So, what is the solution? Let's illustrate it in the next example:
function setLocation(city) { var country = "France"; function printLocation() { console.log("You are in " + city + ", " + country); } printLocation(); } setLocation("Paris"); // 输出:You are in Paris, France
What we do here is put the duplicate code patterns (console.log(item)
and var date = new Date()
) into a separate general function (publish()
) and only keeps specific data in other functions - these The function is now a callback function. In this way, using the same function, we can print relevant information about various related things - messages, articles, books, magazines, etc. The only thing you need to do is create a special callback function for each type and pass it as an argument to the publish()
function.
Execute function expressions immediately (IIFE)
Execute the function expression immediately, or IIFE (pronounced "ify"), is a function expression (named or anonymous) that is executed immediately after it is created.
There are two slightly different syntax variants of this mode:
function setLocation(city) { var country = "France"; function printLocation() { console.log("You are in " + city + ", " + country); } return printLocation; } var currentLocation = setLocation("Paris"); currentLocation(); // 输出:You are in Paris, France
To convert a regular function to IIFE, you need to perform two steps:
Three more things to remember:
First of all, if you assign a function to a variable, you don't need to enclose the entire function in parentheses, because it's already an expression:
function printLocation () { console.log("You are in " + city + ", " + country); }
Secondly, the IIFE ends with a semicolon, otherwise your code may not work properly.
Thirdly, you can pass parameters to IIFE (it is a function after all), as shown in the following example:
function cityLocation() { var city = "Paris"; return { get: function() { console.log(city); }, set: function(newCity) { city = newCity; } }; } var myLocation = cityLocation(); myLocation.get(); // 输出:Paris myLocation.set('Sydney'); myLocation.get(); // 输出:Sydney
Passing a global object as a parameter to IIFE is a common pattern to access it inside a function without using a window
object, which makes the code independent of the browser environment. The following code creates a variable global
which will reference the global object no matter what platform you are using:
function showMessage(message) { setTimeout(function() { alert(message); }, 3000); } showMessage('Function called 3 seconds ago');
This code works in the browser (the global object is window
) or in the Node.js environment (we use special variable global
to refer to the global object).
One of the great benefits of IIFE is that when using it, you don't have to worry about contaminating the global space with temporary variables. All variables you define inside IIFE will be local. Let's check it out:
<!-- HTML --> <button id="btn">Click me</button> <!-- JavaScript --> function showMessage() { alert('Woohoo!'); } var el = document.getElementById("btn"); el.addEventListener("click", showMessage);
In this example, the first console.log()
statement works fine, but the second statement fails because the variables today
and currentTime
become local variables due to IIFE.
We already know that closures retain references to external variables, so they return the latest/updated values. So, what do you think is the output of the following example?
function setLocation(city) { var country = "France"; function printLocation() { console.log("You are in " + city + ", " + country); } printLocation(); } setLocation("Paris"); // 输出:You are in Paris, France
You may expect the name of the fruit to be printed one by one at a interval of seconds. However, in fact, the output is four times "undefined". So, what's the problem?
The problem is that in the statement, the value of console.log()
is equal to 4 for each iteration of the loop. And, since we have nothing at indexing 4 in the i
array, the output is "undefined". (Remember, in JavaScript, the index of the array starts at 0.) When fruits
is equal to 4, the loop terminates. i
variable. We do this by turning off the i
method in IIFE and defining a private variable to hold the current copy of setTimeout()
. i
function setLocation(city) { var country = "France"; function printLocation() { console.log("You are in " + city + ", " + country); } return printLocation; } var currentLocation = setLocation("Paris"); currentLocation(); // 输出:You are in Paris, France
function printLocation () { console.log("You are in " + city + ", " + country); }
Conclusion
The purpose of this tutorial is to introduce these basic concepts as clearly and concisely as possible—as a simple set of principles or rules. A good understanding of them is the key to becoming a successful and efficient JavaScript developer.To explain the topic presented here in more detail and in-depth, I suggest you read "You Don't Know JS: Scopes and Closures" by Kyle Simpson.
(The subsequent content, namely the FAQ part, has been omitted due to the length of the article. If necessary, please ask specific questions.)
The above is the detailed content of Demystifying JavaScript Closures, Callbacks and IIFEs. For more information, please follow other related articles on the PHP Chinese website!