我想知道这是什么意思:
(function () {
})();
这是在说document。onload吗?
我想知道这是什么意思:
(function () {
})();
这是在说document。onload吗?
当前回答
通常,我们不会在程序中写入函数后立即调用它。 简单来说,当您在函数创建后立即调用它时,它被称为IIFE——一个漂亮的名字。
其他回答
Normally, JavaScript code has global scope in the application. When we declare global variable in it, there is a chance for using the same duplicate variable in some other area of the development for some other purpose. Because of this duplication there may happen some error. So we can avoid this global variables by using immediately invoking function expression , this expression is self-executing expression.When we make our code inside this IIFE expression global variable will be like local scope and local variable.
我们可以通过两种方式创建IIFE
(function () {
"use strict";
var app = angular.module("myModule", []);
}());
OR
(function () {
"use strict";
var app = angular.module("myModule", []);
})();
在上面的代码片段中,“var app”现在是一个局部变量。
还有一个用例是内存,缓存对象不是全局的:
var calculate = (function() {
var cache = {};
return function(a) {
if (cache[a]) {
return cache[a];
} else {
// Calculate heavy operation
cache[a] = heavyOperation(a);
return cache[a];
}
}
})();
IIFE(立即调用函数表达式)是一个在脚本加载和退出时立即执行的函数。
考虑下面写在life .js文件中的函数
(function(){
console.log("Hello Stackoverflow!");
})();
上面的代码将在你加载life .js时立即执行,并打印'Hello Stackoverflow!在开发人员工具控制台。
有关详细解释,请参阅立即调用函数表达式(IIFE)
立即调用函数表达式(IIFE)是一种在创建时立即执行的函数。它与任何事件或异步执行没有关联。你可以定义一个IIFE,如下所示:
(function() {
// all your code here
// ...
})();
第一对括号函数(){…}将括号内的代码转换为表达式。第二对括号调用由表达式生成的函数。
IIFE也可以描述为一个自我调用的匿名函数。它最常见的用法是限制通过var创建的变量的作用域,或者封装上下文以避免名称冲突。
自执行匿名函数。它在创建时立即执行。
举个简单的例子,说明这个方法很有用:
function prepareList(el){
var list = (function(){
var l = [];
for(var i = 0; i < 9; i++){
l.push(i);
}
return l;
})();
return function (el){
for(var i = 0, l = list.length; i < l; i++){
if(list[i] == el) return list[i];
}
return null;
};
}
var search = prepareList();
search(2);
search(3);
因此,不是每次都创建一个列表,而是只创建一次(开销更少)。