我想知道这是什么意思:
(function () {
})();
这是在说document。onload吗?
我想知道这是什么意思:
(function () {
})();
这是在说document。onload吗?
当前回答
这是一个自调用匿名函数。
查看W3Schools对自调用函数的解释。
函数表达式可以“自调用”。 自动调用(启动)自调用表达式,无需 被称为。 函数表达式将自动执行 后面跟着()。 不能自调用函数声明。
其他回答
从这里开始:
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);
})();
不需要比这更复杂了。
立即调用的函数表达式(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
它只是一个匿名函数,在创建后立即执行。
这就像你把它赋值给一个变量,然后在后面使用它,只是没有变量:
var f = function () {
};
f();
在jQuery中,有一个类似的构造,你可能会想到:
$(function(){
});
这是绑定就绪事件的简写形式:
$(document).ready(function(){
});
但是上面的两个结构都不是iife。
它声明了一个匿名函数,然后调用它:
(function (local_arg) {
// anonymous function
console.log(local_arg);
})(arg);
这是一个自调用匿名函数。
查看W3Schools对自调用函数的解释。
函数表达式可以“自调用”。 自动调用(启动)自调用表达式,无需 被称为。 函数表达式将自动执行 后面跟着()。 不能自调用函数声明。