i am starting to look at JS in more detail and after testing out some code i have come up with this situation:

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

The output from the console is as follows:

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

Can someone please explain the behavior as i cannot get my head around it.

I understand the the first function is an IIFE and it is being executed immediately when it is created. My only problem is how does the passed parameters be passed to the internal function?

Thanks in advance for the information and comments

有帮助吗?

解决方案

Alright, let me see if I can unwrap this for you:

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

First, I'm going to split out the IFFE into a function statement. It will work the same, but be more like traditional code:

// 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));

The value hello is now our action function.

The IFFE syntax has the following advantages:

  • Since it is an anonymous function, you aren't using a name or cluttering the global object.
  • The code is more "in-line" instead of being split into two separate pieces.

Might help, by the way, if I explain the difference between a function statement and a function expression.

A function statement looks like this:

function functionStatemnt() {
...
}

The functionStatement is available at compile done. That code doesn't need executed in order to be available.

A function expression is more like:

var functionExpression = function() {
...
};

And an IFFE is a function expression that immediately invokes. Gives you a way to create a scope and "hide" variables.

var myCounter = function() {
  var counter = 0;
  return function() {
    return counter++;
  }
}

console.log(myCounter());
console.log(myCounter());
console.log(myCounter());
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top