Home > Web Front-end > JS Tutorial > IIFE Use Cases: Immediately Invoked Function Expressions In Action

IIFE Use Cases: Immediately Invoked Function Expressions In Action

Mary-Kate Olsen
Release: 2025-01-27 10:31:09
Original
603 people have browsed it

IIFE Use Cases: Immediately Invoked Function Expressions In Action

The functional expression (IIFE) immediately called, also known as the self -execution function, is a code block defined and executed immediately after creation. Internal functions can use keywords (traditional methods) or arrow functions. In any way, the entire function is included in a pair of brackets, and then with a pair of brackets. This second pair of brackets is to call the operator, which allows the function to execute immediately.

function Traditional grammar that uses the function declaration:

Arrow function syntax:
<code class="language-javascript">(
    function () {
        console.log('IIFE called');
    }
)();</code>
Copy after login

Now we know what is IIFE, and the next question is why it is useful? The following are some cases:
<code class="language-javascript">(
    () => console.log('IIFE with arrow function called')
)();</code>
Copy after login

By creating a new scope to avoid pollution, global naming space

    Create closures with private variables
  • Used to perform asynchronous and waiting functions
  • The creation of the module
  • In fact, a large part of my daily work is to use Puppeteer to perform automated testing. These Puppeteer scripts are huge IIFE (usually thousands of presidents), which run the code of the test application user interface (UI). In any case, let's continue to discuss our use cases.
Avoid the global naming space of pollution

What does this mean? It essentially means a conflict between the name between the global variables and the local variable of the same name. This becomes more obvious in large enterprise applications. In large enterprise applications, the possibility of reusing variable names will increase, especially when multiple developers handle the same application. The following example illustrates this.

After executing this code, the output is as follows:

<code class="language-javascript">// 全局作用域
const value = "此变量位于全局作用域中,名为 'value'。";
const stateLocation = () => console.log("现在位于全局作用域");

stateLocation();
console.log(value);
console.log("*********************************************************");

(
    function () {
        // 函数作用域
        const value = "此变量位于函数作用域中,即使重用了变量名 'value',也避免了全局污染";
        const stateLocation = () => console.log("现在位于 IIFE 的函数作用域");

        stateLocation();
        console.log(value);
    }
)();</code>
Copy after login

Create closures with private variables

<code>现在位于全局作用域
此变量位于全局作用域中,名为 'value'。
*********************************************************
现在位于 IIFE 的函数作用域
此变量位于函数作用域中,即使重用了变量名 'value',也避免了全局污染</code>
Copy after login
Looking back, closing is an internal function that can access variables in the external function scope. This IIFE example of this calculation circular area illustrates this. In addition, the variables in external functions are private because it cannot be accessed outside the function.

Output:

<code class="language-javascript">const areaOfCircle = (
    function () {
        const pi = Math.PI; // 私有变量
        return function (radius) { // 具有访问外部作用域私有变量的闭包
            return pi * (radius ** 2);
        };
    }
)();

const areaWithRadius2 = areaOfCircle(10);
console.log('半径为 10 的圆的面积是', areaWithRadius2);
// console.log('PI = ', pi); // ReferenceError: pi is not defined</code>
Copy after login
Used to perform asynchronous and waiting functions

IIFE can also be used to perform asynchronous operations, such as network calls. The following examples obtain the list of the items to be obtained from the analog server.
<code>半径为 10 的圆的面积是 314.1592653589793</code>
Copy after login

The creation of the module

This is a module using basic physical equations. It can be exported and used by other programs. I will discuss this further in another article "Using the IIFE Module mode to build a command line physical computing application". Please pay attention to the use of private variables and closures.
<code class="language-javascript">(
    async function () {
        const response = await fetch('https://dummyjson.com/todos');
        const todosObject = await response.json();
        const todoList = todosObject.todos.map(todo => todo.todo);
        console.log(todoList);
    }
)();</code>
Copy after login

It can be seen that IIFE has countless use cases. It can improve the security of data by packaging data and adding modularization to applications.

The above is the detailed content of IIFE Use Cases: Immediately Invoked Function Expressions In Action. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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