search
HomeWeb Front-endJS TutorialDemystifying JavaScript Closures, Callbacks and IIFEs

深入浅出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
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

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

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

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

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:

  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);
}

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

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

function printLocation () {
  console.log("You are in " + city + ", " + country);
}
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
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
Replace String Characters in JavaScriptReplace String Characters in JavaScriptMar 11, 2025 am 12:07 AM

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

Build Your Own AJAX Web ApplicationsBuild Your Own AJAX Web ApplicationsMar 09, 2025 am 12:11 AM

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

10 jQuery Fun and Games Plugins10 jQuery Fun and Games PluginsMar 08, 2025 am 12:42 AM

10 fun jQuery game plugins to make your website more attractive and enhance user stickiness! While Flash is still the best software for developing casual web games, jQuery can also create surprising effects, and while not comparable to pure action Flash games, in some cases you can also have unexpected fun in your browser. jQuery tic toe game The "Hello world" of game programming now has a jQuery version. Source code jQuery Crazy Word Composition Game This is a fill-in-the-blank game, and it can produce some weird results due to not knowing the context of the word. Source code jQuery mine sweeping game

How do I create and publish my own JavaScript libraries?How do I create and publish my own JavaScript libraries?Mar 18, 2025 pm 03:12 PM

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

jQuery Parallax Tutorial - Animated Header BackgroundjQuery Parallax Tutorial - Animated Header BackgroundMar 08, 2025 am 12:39 AM

This tutorial demonstrates how to create a captivating parallax background effect using jQuery. We'll build a header banner with layered images that create a stunning visual depth. The updated plugin works with jQuery 1.6.4 and later. Download the

Getting Started With Matter.js: IntroductionGetting Started With Matter.js: IntroductionMar 08, 2025 am 12:53 AM

Matter.js is a 2D rigid body physics engine written in JavaScript. This library can help you easily simulate 2D physics in your browser. It provides many features, such as the ability to create rigid bodies and assign physical properties such as mass, area, or density. You can also simulate different types of collisions and forces, such as gravity friction. Matter.js supports all mainstream browsers. Additionally, it is suitable for mobile devices as it detects touches and is responsive. All of these features make it worth your time to learn how to use the engine, as this makes it easy to create a physics-based 2D game or simulation. In this tutorial, I will cover the basics of this library, including its installation and usage, and provide a

Auto Refresh Div Content Using jQuery and AJAXAuto Refresh Div Content Using jQuery and AJAXMar 08, 2025 am 12:58 AM

This article demonstrates how to automatically refresh a div's content every 5 seconds using jQuery and AJAX. The example fetches and displays the latest blog posts from an RSS feed, along with the last refresh timestamp. A loading image is optiona

How do I optimize JavaScript code for performance in the browser?How do I optimize JavaScript code for performance in the browser?Mar 18, 2025 pm 03:14 PM

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),