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
有帮助吗?

解决方案

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);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top