好吧,让我看看我能不能帮你解开这个:
var hello = function ()
{
console.log(arguments);
return (function(x,y){
console.log(arguments);
return x*y;
});
}();
console.log(hello(2,5));
首先,我将把 IFFE 拆分成一个函数语句。它的工作原理相同,但更像传统代码:
// Create our function
function action(x, y) {
console.log(arguments);
return x*y;
}
var hello = function ()
{
console.log(arguments);
//Here we are returning a REFERENCE to a function that already exists.
// We are *not* running the `action` function -- just getting its
// reference so it can be called later.
return action;
}();
// At this point in time, if you did a
console.log(hello)
// You'd see that it just points to the `action` function -- since that is what the
// IIFE returned.
console.log(hello(2,5));
该值hello
现在是我们的action
函数。
IFFE 语法具有以下优点:
- 由于它是一个匿名函数,因此您不会使用名称或弄乱全局对象。
- 代码更“内联”,而不是被分成两个单独的部分。
function statement
顺便说一句,如果我解释 a和 a之间的区别,可能会有所帮助function expression
。
函数语句如下所示:
function functionStatemnt() {
...
}
functionStatement 在编译完成时可用。该代码不需要执行即可。
函数表达式更像:
var functionExpression = function() {
...
};
IFFE 是一个立即调用的函数表达式。为您提供一种创建范围和“隐藏”变量的方法。
var myCounter = function() {
var counter = 0;
return function() {
return counter++;
}
}
console.log(myCounter());
console.log(myCounter());
console.log(myCounter());