admin管理员组

文章数量:1289349

Closures store their outer variables by reference (and not by value). In the below code, however, I want to store by value. Can anyone show me how to do it using IIFE?

var i = -1;
var f = function () {
    return i; // I want to capture i = -1 here!
};
i = 1;
f();    // => 1, but I want -1

Closures store their outer variables by reference (and not by value). In the below code, however, I want to store by value. Can anyone show me how to do it using IIFE?

var i = -1;
var f = function () {
    return i; // I want to capture i = -1 here!
};
i = 1;
f();    // => 1, but I want -1
Share Improve this question edited Jan 4, 2014 at 7:27 cmutex asked Jan 4, 2014 at 6:56 cmutexcmutex 1,6081 gold badge14 silver badges28 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 11

What you've posted is in fact not an IIFE: that stands for immediately invoked function expression; you have a function but you're not immediately invoking it!

That aside, the idea here is to store the interesting bit of state in a function argument, so that it's a distinct reference. You do that by creating another function (the Function Expression part), and then invoking it with the globals whose state you want to capture (the Immediately Invoked part). Here's what it looks like:

var i = -1;
var f = (function(state) { // this will hold a snapshot of i
            return function() {
               return state; // this returns what was in the snapshot
            };
         })(i); // here we invoke the outermost function, passing it i (which is -1).
                // it returns the inner function, with state as -1
i = 1; // has no impact on the state variable
f(); // now we invoke the inner function, and it looks up state, not i

As IIFE - Immediately invoke the function.

var i = -1;
var f = function () {
    return i; // I want to capture i = -1 here!
}();// invoked here
i = 1;
console.log(f);

本文标签: Javascript closure and IIFE (immediately invoked function expressions)Stack Overflow