Two ways to write the function immediately

1、 (function() {})()  

2、(function(){}())

Benefits of immediate function execution: Creates an isolated scope. Avoids naming conflict issues.

important point:

  1. Immediate execution function: a function that can be executed immediately without calling
  2. You can also pass parameters in, the second parentheses can be seen as calling a function

  3. You can give the immediate execution function a name

  4. When there are multiple immediate execution functions, a semicolon should be added at the end of the immediate execution functions.

example:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <script>
        // 1.立即执行函数: 不需要调用,立马能够自己执行的函数
        function fn() {
            console.log(1);

        }
        fn();
        // 2. 写法 也可以传递参数进来
        // 1.(function() {})()    或者  2. (function(){}());
        (function(a, b) {
            console.log(a + b);
            var num = 10;
        })(1, 2); // 第二个小括号可以看做是调用函数
        (function sum(a, b) {
            console.log(a + b);
            var num = 10; // 局部变量
        }(2, 3));
        // 3. 立即执行函数最大的作用就是 独立创建了一个作用域, 里面所有的变量都是局部变量 不会有命名冲突的情况
    </script>
</body>

</html>

Reference: Dark Horse Programmer

Guess you like

Origin blog.csdn.net/qq_51387458/article/details/129962983