[英]Javascript closure and IIFE (immediately invoked function expressions)
閉包通過引用(而不是值)存儲它們的外部變量。 但是,在下面的代碼中,我想按值存儲。 任何人都可以告訴我如何使用IIFE嗎?
var i = -1;
var f = function () {
return i; // I want to capture i = -1 here!
};
i = 1;
f(); // => 1, but I want -1
您發布的內容實際上不是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
作為IIFE - 立即調用該函數。
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 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.