Home > Web Front-end > JS Tutorial > Demystifying JavaScript Closures, Callbacks and IIFEs

Demystifying JavaScript Closures, Callbacks and IIFEs

William Shakespeare
Release: 2025-02-20 08:43:09
Original
568 people have browsed it

深入浅出JavaScript闭包、回调函数和立即执行函数表达式 (IIFE)

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

  • JavaScript closures are functions that can access their parent scope variables. Even if the parent function has been executed, the closure can still remember and manipulate these variables.
  • The callback function is a function passed as a parameter to other functions, which are then executed within an external function, providing a way to delay execution or maintain the order of asynchronous operations.
  • Execute now function expression (IIFE) is a function that is executed immediately after definition to protect the scope of variables and prevent global scope contamination.
  • Closures can both read and update variables stored in their scope, and these updates are visible to any closure that accesses these variables, which proves that the closure stores references to the variables, and Not a value.
  • Using IIFE helps create private scopes within functions, thereby better managing variables and preventing external access to these variables.
  • The combination of these concepts (closures, callback functions, and IIFE) provides powerful tools for writing concise, efficient and secure JavaScript code to encapsulate functionality and avoid global scope contamination.

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:

    Any variables and parameters in its own function scope
  • Any variables and parameters of external (parent) function
  • Any variable in global scope
So you may have used the closure without knowing it. But our goal is not just to use them—but to understand them. If we don't understand how they work, we can't use them correctly. To do this, we break down the above closure definition into three easy-to-understand key points.

Point 1: You can refer to variables defined outside the current function.

In this code example, the

function refers to the
function setLocation(city) {
  var country = "France";

  function printLocation() {
    console.log("You are in " + city + ", " + country);
  }

  printLocation();
}

setLocation("Paris"); // 输出:You are in Paris, France
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login
variable and

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
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

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 currentLocationalert(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
Copy after login
Copy after login
Copy after login
Copy after login

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);
}
Copy after login
Copy after login
Copy after login
Copy after login

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

We can use this behavior to store private data in objects. Instead of storing data as an attribute of an object, store it as a variable in the constructor and then use a closure as a way to reference those variables.

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
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

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
Copy after login
Copy after login
Copy after login
Copy after login

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);
}
Copy after login
Copy after login
Copy after login
Copy after login

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
Copy after login
Copy after login

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
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

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
Copy after login
Copy after login
Copy after login
Copy after login

To convert a regular function to IIFE, you need to perform two steps:

  1. You need to enclose the entire function in brackets. As the name implies, IIFE must be a function expression, not a function definition. Therefore, the purpose of enclosing parentheses is to convert function definitions into expressions. This is because in JavaScript everything in parentheses are treated as expressions.
  2. You need to add a pair of brackets at the end (variant 1), or after closing the braces (variant 2), which causes the function to execute immediately.

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);
}
Copy after login
Copy after login
Copy after login
Copy after login

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
Copy after login
Copy after login

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');
Copy after login

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);
Copy after login

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
Copy after login
Copy after login
Copy after login
Copy after login
Copy after login

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

To solve this problem, we need to provide a new scope for each function created by the loop - this will capture the current state of the

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
Copy after login
Copy after login
Copy after login
Copy after login
We can also use the following variant, which performs the same task:

function printLocation () {
  console.log("You are in " + city + ", " + country);
}
Copy after login
Copy after login
Copy after login
Copy after login
IIFE is usually used to create scopes to encapsulate modules. Within the module, there is a self-contained private scope that prevents accidental modifications. This technique is called module pattern and is a powerful example of using closure management scopes, which is widely used in many modern JavaScript libraries such as jQuery and Underscore.

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template