Javascript闭包和IIFE(立即调用函数表达式)

时间:2014-01-04 06:56:46

标签: javascript closures iife

Closures通过引用(而不是值)存储它们的外部变量。但是,在下面的代码中,我想按值存储。任何人都可以告诉我如何使用IIFE吗?

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

2 个答案:

答案 0 :(得分:9)

您发布的内容实际上不是IIFE:代表立即调用的函数表达式;你有一个功能,但你没有立即调用它!

除此之外,这里的想法是在函数参数中存储有趣的状态位,以便它是一个独特的引用。您可以通过创建另一个函数(函数表达式部分),然后使用要捕获其状态的全局变量(立即调用的部分)来调用它。这是它的样子:

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

答案 1 :(得分:0)

与IIFE一样-立即调用该函数。

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