admin管理员组

文章数量:1278818

I'm familiar with the IIFE way to execute a function:

(function(){
    //stuff
}());
//immediately invoked, parsed as an expression

And this way in which I can assign a name to a function just by declaring it like any other object:

var theFunction = function(){
    //stuff
}
//can be executed with theFunction();

But today I saw the two bined like this:

var theFunction = (function(){ 
    //stuff
}());

What does this do, or what advantage could it provide?

I'm familiar with the IIFE way to execute a function:

(function(){
    //stuff
}());
//immediately invoked, parsed as an expression

And this way in which I can assign a name to a function just by declaring it like any other object:

var theFunction = function(){
    //stuff
}
//can be executed with theFunction();

But today I saw the two bined like this:

var theFunction = (function(){ 
    //stuff
}());

What does this do, or what advantage could it provide?

Share Improve this question asked Aug 21, 2013 at 19:16 12527481252748 15.4k34 gold badges117 silver badges241 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 11

What you're showing there is not an IIFE with a name (which does exist). It's a variable that holds the return value of the IIFE.


A real IIFE with a name would be this:

(function myName (){
    // code here...
}());

The use for a name on an IIFE is two-fold:

  1. For self reference. If the function wants to call itself (recursively), it can use that name (instead of arguments.callee, which doesn't work in strict mode).

  2. It helps with debugging, as it'll show you the function's name in the stack trace.

theFunction will be set to the return value of the IIFE. This is generally known as the module pattern

It is a good way to allow an object to have private variables that aren't available in the global space, but that are still visible to the modules own functions, and is one of the best ways to namespace your code as a result.

for example, here is a simple private variable with getters and setters example.

It would be easy to modify this to only allow certain values to be set, limiting access to the property.

var module = (function(){
  var x = {};
  var private = 2;

  x.setPrivate = function(val) {
     private = val;
  }

  x.getPrivate = function() {
    return private;
  }

  return x;

}());

As others have pointed out, this is different from a named IIFE, which you might use if you wanted to refer to the function from within itself

(function foo(){
  //recursive foo call
  foo();
}()):

This assigns the result of an IIFE to a variable. This can be very useful if you need a bunch of auxiliary variables to initialize the variable but don't want to pollute the namespace. Or it enables you to construct functions which have access to other auxiliary non-global "private" functions.

本文标签: javascriptWhat is the practical use of an IIFE with a nameStack Overflow