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
2 Answers
Reset to default 11What 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
版权声明:本文标题:Javascript closure and IIFE (immediately invoked function expressions) - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741417253a2377588.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论