Encountered some code that's using IIFEs in an expression rather than just a normal function.

var custom_type = (function() {
    return $('#myDiv').attr('custom_type');
})();

Normally I would write this as something like:

var custom_type = function() {
    return $('#myDiv').attr('custom_type');
};

What's the reason for the IIFE? The only thing I can think of is that the IIFE might assign the custom_type variable only once at the beginning whereas the second might continue to check for the updated type every time the variable is referenced.

有帮助吗?

解决方案

In this example, you can dispense with the function altogether and just do:

var custom_type = $('#myDiv').attr('custom_type');

However in general you can use an IIFE for more complex "just-in-time" computation of variable assignments - I like to use them if I need to iterate over something, so I can have i without polluting the current scope.

In your second example, though, the result is completely different - you will need to call the function custom_type() to get the current value, whereas the first piece of code will get its value once, and the variable will hold that value.

其他提示

The IIFE will actually run (immediately-invoked function expression), so the variable will be set to its response.

Here's a JSFiddle to demonstrate this, watch your JS console for the output: http://jsfiddle.net/Y4JmT/1/

Code Here:

var custom_type = (function() {
    return 'foo';
})();

var custom_type2 = function() {
    return 'bar';
};

console.log('iife = ' + custom_type);
console.log('non-iife = ' + custom_type2);

In your JS console you'll see something similar to:

iife = foo 

and

non-iife = function () {
    return 'bar';
} 

The first one of yours (IIFE) executes the function and store its result, the seconds stores function as definition.

(function(x) {
    return x * 2;
})(5);

You are making a call like to normal funciton: func(arg1, arg2), but instead of function name you pass whole function definition, so the above would return 10 like:

function multiply(x) {
    return x * 2;
}

multiply(5);

They mean the same thing, you are making calls. Unlikely the first, second is definition plus a call.

IIFEs allow you to invoke a function (anonymous or otherwise) at the point of creation. Have you looked at this? http://benalman.com/news/2010/11/immediately-invoked-function-expression/

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top