![](/img/trans.png)
[英]Difference between calling an anonymous function directly vs calling it by variable?
[英]variable calling function and calling function directly
我正在學習 JavaScript 和 Manning 的書 Get Programming with JavaScript(作者 John Larsen)。 在第 11 章清單 11.8 中,代碼:
var getCounter = function () {
var counter = 0;
var countUpBy1 = function () {
counter = counter + 1;
return counter;
};
return countUpBy1;
};
var count = getCounter();
我正在使用 jsbin.com 進行實驗和學習。 在控制台中:
Q1) 為什么調用count(),結果並不總是1? 為什么呢,計數器一開始就設置為0,在countUpBy1之前,countUpBy1里面的計數器不應該也是0嗎?
Q2) 為什么調用 getCounter() 與 count() 不同? 調用 count() 得到一個數字(這是我所期望的),但調用 getCounter() 得到我:
function () {
counter = counter + 1;
return counter;
}
感謝您提前解釋。
4/Nov: @DavidFleeman: Am I correct in my understand to first question (I read all 3 links, plus JavaScript Closures 101: What is a closure ?, I never understood JavaScript closures & JavaScript Closures Explained by Mailing a Package :
(刪除了我對逐步關閉的理解)
11 月 12 日: 我從來不理解 JavaScript 閉包多讀幾次這個鏈接,它比我解釋得更好。
這些嵌套方法創建了一個閉包,其中初始化只發生一次,並且每次都返回嵌套的內部方法。 請閱讀此鏈接以了解:
https://www.w3schools.com/js/js_function_closures.asp
如果您更喜歡 MDN,請使用以下鏈接。 但是,上面的鏈接有我認為與成員的情況相匹配的示例:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures
對於更多細節,這似乎是一個深思熟慮的解釋:
https://blogs.msdn.microsoft.com/ericlippert/2003/09/17/what-are-closures/
閱讀上面的相同鏈接,您可以看到如何定義 getCounter() 以完全按照您的要求執行。 您必須將其定義為自調用 function。 在您的示例中,它不是使用自調用語法定義的。 如果您想使用 getCounter() 而不是 count() 來定義它,請參見下面的示例。
var getCounter = (function () {
var counter = 0;
var countUpBy1 = function () {
counter = counter + 1;
return counter;
};
return countUpBy1;
})();
getCounter();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.