我想知道这是什么意思:
(function () {
})();
这是在说document。onload吗?
我想知道这是什么意思:
(function () {
})();
这是在说document。onload吗?
当前回答
这个函数称为自调用函数。自调用(也称为自执行)函数是在定义之后立即调用(已调用)的无名(匿名)函数。点击这里阅读更多
这些函数的作用是,当函数被定义时,函数立即被调用,这节省了时间和额外的代码行(与在单独的行上调用相比)。
这里有一个例子:
(函数(){ Var x = 5 + 4; console.log (x); }) ();
其他回答
(function () {
})();
这被称为IIFE(立即调用函数表达式)。它是著名的JavaScript设计模式之一,是现代Module模式的核心和灵魂。顾名思义,它在创建后立即执行。此模式创建一个隔离的或私有的执行范围。
在ECMAScript 6之前的JavaScript使用词法作用域,因此IIFE用于模拟块作用域。(在ECMAScript 6中,通过引入let和const关键字,块范围是可能的。) 关于词汇范围问题的参考
用IIFE模拟块作用域
使用IIFE的性能优势是能够通过减少范围查找来将常用的全局对象(如window、document等)作为参数传递。(请记住,JavaScript在局部作用域和全局作用域的链中寻找属性)。因此,在局部作用域中访问全局对象可以减少查找时间,如下所示。
(function (globalObj) {
//Access the globalObj
})(window);
从这里开始:
var b = 'bee';
console.log(b); // global
把它放在一个函数中,它就不再是全局的了——这是你的主要目标。
function a() {
var b = 'bee';
console.log(b);
}
a();
console.log(b); // ReferenceError: b is not defined -- *as desired*
立即调用函数——哎呀:
function a() {
var b = 'bee';
console.log(b);
}(); // SyntaxError: Expected () to start arrow function, but got ';' instead of '=>'
使用括号来避免语法错误:
(function a() {
var b = 'bee';
console.log(b);
})(); // OK now
你可以省略函数名:
(function () { // no name required
var b = 'bee';
console.log(b);
})();
不需要比这更复杂了。
这个函数称为自调用函数。自调用(也称为自执行)函数是在定义之后立即调用(已调用)的无名(匿名)函数。点击这里阅读更多
这些函数的作用是,当函数被定义时,函数立即被调用,这节省了时间和额外的代码行(与在单独的行上调用相比)。
这里有一个例子:
(函数(){ Var x = 5 + 4; console.log (x); }) ();
这是一个自调用匿名函数。
查看W3Schools对自调用函数的解释。
函数表达式可以“自调用”。 自动调用(启动)自调用表达式,无需 被称为。 函数表达式将自动执行 后面跟着()。 不能自调用函数声明。
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”现在是一个局部变量。