我想知道这是什么意思:

(function () {

})();

这是在说document。onload吗?


当前回答

使用自调用匿名函数的原因是它们永远不应该被其他代码调用,因为它们“设置”了要调用的代码(同时为函数和变量提供了作用域)。

换句话说,它们就像在程序开始时“创建类”的程序。在它们被实例化(自动)之后,唯一可用的函数是匿名函数返回的那些函数。然而,所有其他“隐藏”函数仍然存在,以及任何状态(在作用域创建期间设置的变量)。

非常酷。

其他回答

以下代码:

(function () {

})();

称为立即调用函数表达式(IIFE)。

它之所以被称为函数表达式,是因为Javascript中的(yourcode)操作符将其强制转换为表达式。函数表达式和函数声明的区别如下:

// declaration:
function declaredFunction () {}

// expressions:

// storing function into variable
const expressedFunction = function () {}

// Using () operator, which transforms the function into an expression
(function () {})

表达式只是一组可以求值为单个值的代码。对于上面例子中的表达式,这个值是一个单独的函数对象。

在得到表达式后,计算结果为函数对象,然后可以立即使用()操作符调用函数对象。例如:

(函数(){ Const foo = 10;//这里的所有变量都是函数块的作用域 console.log (foo); }) (); console.log (foo);// referenceError foo的作用域是IIFE

为什么这个有用?

当我们处理大型代码库和/或导入各种库时,命名冲突的几率会增加。当我们在IIFE中编写相关(因此使用相同的变量)的代码的某些部分时,所有的变量和函数名都被限定在IIFE的函数括号内。这减少了命名冲突的可能性,让你在命名时更粗心(例如,你不必在它们前面加上前缀)。

这里已经有很多很好的答案了,但这里是我的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。它在创建后立即执行。

它与任何事件的任何事件处理程序(例如document.onload)无关。 考虑第一对括号中的部分:(function(){})();....它是一个正则函数表达式。然后看最后一对(function(){})();,它通常被添加到表达式中来调用函数;在这种情况下,我们之前的表达式。

当试图避免污染全局名称空间时,通常使用此模式,因为在IIFE中使用的所有变量(像在任何其他正常函数中一样)在其作用域之外是不可见的。 这可能就是为什么您将此结构与window的事件处理程序混淆的原因。Onload,因为它经常被这样使用:

(function(){
  // all your code here
  var foo = function() {};
  window.onload = foo;
  // ...
})();
// foo is unreachable here (it’s undefined)

Guffa建议的更正:

函数在创建后立即执行,而不是在解析后执行。整个脚本块在执行其中的任何代码之前都会被解析。此外,解析代码并不自动意味着它被执行,例如,如果IIFE在函数内部,那么直到函数被调用,它才会被执行。

更新 因为这是一个非常流行的话题,值得一提的是,IIFE也可以用ES6的箭头函数来编写(就像Gajus在评论中指出的那样):

((foo) => {
 // do something with foo here foo
})('foo value')

立即调用的函数表达式(IIFE)立即调用函数。这仅仅意味着函数在定义完成后立即执行。

更常见的三个词:

// Crockford's preference - parens on the inside
(function() {
  console.log('Welcome to the Internet. Please follow me.');
}());

//The OPs example, parentheses on the outside
(function() {
  console.log('Welcome to the Internet. Please follow me.');
})();

//Using the exclamation mark operator
//https://stackoverflow.com/a/5654929/1175496
!function() {
  console.log('Welcome to the Internet. Please follow me.');
}();

如果对它的返回值没有特殊要求,那么我们可以这样写:

!function(){}();  // => true
~function(){}(); // => -1
+function(){}(); // => NaN
-function(){}();  // => NaN

或者,它可以是:

~(function(){})();
void function(){}();
true && function(){ /* code */ }();
15.0, function(){ /* code */ }();

你甚至可以这样写:

new function(){ /* code */ }
31.new function(){ /* code */ }() //If no parameters, the last () is not required

使用自调用匿名函数的原因是它们永远不应该被其他代码调用,因为它们“设置”了要调用的代码(同时为函数和变量提供了作用域)。

换句话说,它们就像在程序开始时“创建类”的程序。在它们被实例化(自动)之后,唯一可用的函数是匿名函数返回的那些函数。然而,所有其他“隐藏”函数仍然存在,以及任何状态(在作用域创建期间设置的变量)。

非常酷。