1

我开始更详细地研究 JS,在测试了一些代码之后,我想出了这种情况:

var hello = function ()
    {
        console.log(arguments);
        return (function(x,y){console.log(arguments);return x*y;});
    }();
console.log(hello(2,5));

控制台的输出如下:

[object Arguments] { ... }
[object Arguments] {
  0: 2,
  1: 5
}
10

有人可以解释一下这种行为,因为我无法理解它。

我知道第一个函数是 IIFE,它在创建时立即执行。我唯一的问题是传递的参数如何传递给内部函数?

提前感谢您的信息和评论

4

1 回答 1

2

好吧,让我看看我能不能帮你解开这个:

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());
于 2014-04-17T14:02:47.000 回答