我想知道这是什么意思:

(function () {

})();

这是在说document。onload吗?


当前回答

在ES6语法中(为自己发帖,因为我一直登陆这个页面寻找一个快速的例子):

// simple
const simpleNumber = (() => {
  return true ? 1 : 2
})()

// with param
const isPositiveNumber = ((number) => {
  return number > 0 ? true : false
})(4)

其他回答

它声明了一个匿名函数,然后调用它:

(function (local_arg) {
   // anonymous function
   console.log(local_arg);
})(arg);

IIFE(立即调用函数表达式)是一个在脚本加载和退出时立即执行的函数。

考虑下面写在life .js文件中的函数

(function(){
       console.log("Hello Stackoverflow!");
   })();

上面的代码将在你加载life .js时立即执行,并打印'Hello Stackoverflow!在开发人员工具控制台。

有关详细解释,请参阅立即调用函数表达式(IIFE)

(function () {
})();

这被称为IIFE(立即调用函数表达式)。它是著名的JavaScript设计模式之一,是现代Module模式的核心和灵魂。顾名思义,它在创建后立即执行。此模式创建一个隔离的或私有的执行范围。

在ECMAScript 6之前的JavaScript使用词法作用域,因此IIFE用于模拟块作用域。(在ECMAScript 6中,通过引入let和const关键字,块范围是可能的。) 关于词汇范围问题的参考

用IIFE模拟块作用域

使用IIFE的性能优势是能够通过减少范围查找来将常用的全局对象(如window、document等)作为参数传递。(请记住,JavaScript在局部作用域和全局作用域的链中寻找属性)。因此,在局部作用域中访问全局对象可以减少查找时间,如下所示。

(function (globalObj) {
//Access the globalObj
})(window);

这里已经有很多很好的答案了,但这里是我的2美分:p


你可以使用IIFE(立即调用函数表达式):

Avoiding pollution in the global namespace. Variables defined in IIFE (or even any normal function) don't overwrite definitions in global scope. Protecting code from being accessed by outer code. Everything that you define within the IIFE can be only be accessed within the IIFE. It protects code from being modified by outer code. Only what you explicitly return as the result of function or set as value to outer variables is accessible by outer code. Avoid naming functions that you don't need to use repeatedly. Though it's possible to use a named function in IIFE pattern you don't do it as there is no need to call it repeatedly, generally. For Universal Module Definitions which is used in many JS libraries. Check this question for details.


IIFE通常以以下方式使用:

(function(param){
   //code here
})(args);

您可以省略匿名函数周围的括号(),并在匿名函数之前使用void运算符。

void function(param){
   //code here
}(args);

它是一个函数表达式,它代表立即调用函数表达式(IIFE)。IIFE只是一个在创建后立即执行的函数。因此,函数不必等到调用它才能执行,而是立即执行IIFE。让我们通过示例来构造IIFE。假设我们有一个add函数,它接受两个整数作为参数并返回和 让我们把add函数放到IIFE中,

步骤1:定义函数

function add (a, b){
    return a+b;
}
add(5,5);

Step2:通过将整个函数声明包装到圆括号中来调用函数

(function add (a, b){
    return a+b;
})
//add(5,5);

步骤3:要立即调用函数,只需从调用中删除'add'文本。

(function add (a, b){
    return a+b;
})(5,5);

使用IFFE的主要原因是在函数中保留私有作用域。在javascript代码中,你要确保你没有覆盖任何全局变量。有时您可能会意外地定义一个覆盖全局变量的变量。让我们举个例子。假设我们有一个名为iffe.html的HTML文件,body标签内的代码是-

<body>
    <div id = 'demo'></div>
    <script>
        document.getElementById("demo").innerHTML = "Hello JavaScript!";
    </script> 
</body>

好吧,上面的代码将毫无疑问地执行,现在假设您意外或有意地声明了一个名为document的变量。

<body>
    <div id = 'demo'></div>
    <script>
        document.getElementById("demo").innerHTML = "Hello JavaScript!";
        const document = "hi there";
        console.log(document);
    </script> 
</body>

你将会看到一个SyntaxError:重新声明不可配置的全局属性文档。

但是如果你想要声明一个名为documentmet的变量,你可以使用IFFE来实现。

<body>
    <div id = 'demo'></div>
    <script>
        (function(){
            const document = "hi there";
            this.document.getElementById("demo").innerHTML = "Hello JavaScript!";
            console.log(document);
        })();
        document.getElementById("demo").innerHTML = "Hello JavaScript!";
    </script> 
</body>

输出:

让我们尝试另一个例子,假设我们有一个计算器对象像bellow-

<body>
    <script>
        var calculator = {
            add:function(a,b){
                return a+b;
            },
            mul:function(a,b){
                return a*b;
            }
        }
        console.log(calculator.add(5,10));
    </script> 
</body>

这很神奇,如果我们不小心重新赋值了计算器对象的值。

<body>
    <script>
        var calculator = {
            add:function(a,b){
                return a+b;
            },
            mul:function(a,b){
                return a*b;
            }
        }
        console.log(calculator.add(5,10));
        calculator = "scientific calculator";
        console.log(calculator.mul(5,5));
    </script> 
</body>

是的,你将结束一个TypeError:计算器。Mul不是if .html的函数

但是在IFFE的帮助下,我们可以创建一个私有作用域,在那里我们可以创建另一个变量名计算器并使用它;

<body>
    <script>
        var calculator = {
            add:function(a,b){
                return a+b;
            },
            mul:function(a,b){
                return a*b;
            }
        }
        var cal = (function(){
            var calculator = {
                sub:function(a,b){
                    return a-b;
                },
                div:function(a,b){
                    return a/b;
                }
            }
            console.log(this.calculator.mul(5,10));
            console.log(calculator.sub(10,5));
            return calculator;
        })();
        console.log(calculator.add(5,10));
        console.log(cal.div(10,5));
    </script> 
</body>

输出: