我想知道这是什么意思:
(function () {
})();
这是在说document。onload吗?
我想知道这是什么意思:
(function () {
})();
这是在说document。onload吗?
当前回答
这是一个更深入的解释,为什么你会使用这个:
“使用IIFE的主要原因是确保数据隐私。因为JavaScript的var将变量限定在包含变量的函数内,所以任何在IIFE中声明的变量都不能被外部世界访问。”
http://adripofjavascript.com/blog/drips/an-introduction-to-iffes-immediately-invoked-function-expressions.html
其他回答
自执行函数通常用于封装上下文和避免名称混淆。在(function(){..})()中定义的任何变量都不是全局变量。
的代码
var same_name = 1;
var myVar = (function() {
var same_name = 2;
console.log(same_name);
})();
console.log(same_name);
产生如下输出:
2
1
通过使用这种语法,可以避免与JavaScript代码中其他地方声明的全局变量发生冲突。
它声明了一个匿名函数,然后调用它:
(function (local_arg) {
// anonymous function
console.log(local_arg);
})(arg);
立即调用函数表达式(IIFE)是一种在创建时立即执行的函数。它与任何事件或异步执行没有关联。你可以定义一个IIFE,如下所示:
(function() {
// all your code here
// ...
})();
第一对括号函数(){…}将括号内的代码转换为表达式。第二对括号调用由表达式生成的函数。
IIFE也可以描述为一个自我调用的匿名函数。它最常见的用法是限制通过var创建的变量的作用域,或者封装上下文以避免名称冲突。
这是自调用匿名函数。它在定义时执行。这意味着该函数被定义并在定义之后立即调用自身。
语法的解释是:第一个()圆括号内的函数是没有名称的函数,由下一个();括号,你可以理解它在定义时被调用。你可以在第二个()圆括号中传递任何参数它会在第一个圆括号中的函数中被抓取。请看这个例子:
(function(obj){
// Do something with this obj
})(object);
在这里,你传递的“对象”将在函数中通过“obj”访问,因为你在函数签名中抓取它。
这里已经有很多很好的答案了,但这里是我的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);