簡體   English   中英

JavaScript閉包返回函數

[英]Javascript Closure Return Function

我試圖學習有關javascript閉包的信息,並且遇到了以下示例:

function counter() {
    var count = 0;
    return function() {
        alert(count++);
    }
}
var count = counter();
count();
count();
count();

對我來說有意義,我的問題是,為什么這不起作用?

var count = function() {
    var count = 0;
    return function() {
        alert(count++);
    }
};
count();
count();
count();

在我看來,這應該是完全相同的事情,但也許我只是缺少明顯的東西,請協助。

為了使第二個方法起作用,您將需要像這樣調用返回的函數:

var count = function() {
    var count = 0;
    return function() {
        alert(count++);
    }
};
count()();

但是,這樣做不會增加計數數,因為它沒有像第一個示例那樣存儲在任何地方,因為第一個示例中變量count保存了函數。

因此,如果要保留count的值,請使用第一種方法,其中說var count = counter()

希望這能說明問題!

我會嘗試在您的代碼中給出一個很好的解釋:

function counter() {
    var count = 0;

    // By calling the function counter (adding a '()' after its name) you are returning a brand new anonymous function
    return function() { // **Reference 1**
        alert(count++);
    }
}

// Here, the count variable is actually the anonymous function you returned in the **Reference 1**
var count = counter();

// In this line, you are calling the anonymous function (adding the '()' after its new name 'count')
count();

上面的解釋解釋了為什么這樣做。 因為,首先調用一個函數,該函數返回一個匿名函數並將其分配給變量count。 然后您通過在其名稱后添加“()”來調用該函數,從而執行alert(count++)

現在,為什么另一個示例不起作用? 我想現在很明顯了:

var count = function() {
    var count = 0;
    return function() { // **Reference 2**
        alert(count++);
    }
};

// Here you are calling the count function which returns the anonymous function in the line **Reference 2**.
count(); // So, long story short, this call only returns the anonymous function.

您應該嘗試在其后添加第二個'()': count()(); 這也應該工作,因為第一個'()'返回匿名函數,而第二個'執行返回的匿名函數。

希望這可以幫助!

在使用閉包之前,必須調用外部函數創建閉包並獲取返回的內部函數,然后保留該返回結果,然后可以隨后調用此函數使用閉包。 因此,在第二個示例中,您必須調用count()並保留其返回結果,然后將該返回結果用於后續調用。

如果將其更改為第二個示例,則該示例將起作用(看起來與第一個示例幾乎相同):

 // log output for purposes of the snippet function log(x) { var div = document.createElement("div"); div.innerHTML = x; document.body.appendChild(div); } var counter = function() { var count = 0; return function() { log(count++); } }; // get the inner function and create the closure var count = counter(); count(); count(); count(); 

如您所見,這僅與第一個示例有所不同,因為該counter是函數表達式而不是函數定義。 除了定義counter的時間之外,第二個代碼示例沒有什么不同,因此實現方式必須相同。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM