2016-03-01 55 views
2

我想了解在JavaScript關閉和我碰到下面的例子就是:的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(); 

對我來說,它看起來像它應該是完全一樣的事情,但也許我只是缺少明顯的東西,請幫助。

回答

1

,我會盡量給你的代碼一個不錯的解釋權:

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(); 

上述解釋解釋爲什麼這個工程。因爲,首先你調用了一個函數,它返回一個匿名函數並將其分配給變量計數。然後你通過在其名稱後面加上'()'來調用該函數,該函數執行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()();。這應該也可以,因爲第一個'()'返回匿名函數,第二個執行返回的匿名函數。

希望這會有所幫助!

+0

非常感謝大家,所有的答案都很有幫助,我只是很感激在這裏額外付出代價,並在代碼中解釋答案,我現在完全明白了。 – SeptimaEspada

+0

很棒@SeptimaEspada。這是一個非常簡單的概念,對於Javascript高級編程非常有用。非常樂意幫助你! :) – wilsotobianco

0

在使用閉包之前,必須調用外部函數來創建閉包並獲取返回的內部函數,然後保留該返回結果,然後可以調用後續時間來使用閉包。因此,在第二個示例中,您必須致電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的時間之外,第二個代碼示例沒有區別,因此實現需要相同。

+0

是的,這很有道理,謝謝。 – SeptimaEspada

1

爲了讓你的第二個方法來工作,你將需要調用返回的功能是這樣的:

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

但是,這樣做,你的計數量不會增加,因爲它沒有被任何地方像存儲在第一個示例中,變量count包含該函數。

所以,如果你想保留計數的值,使用在那裏你說var count = counter()

希望第一種方法是清除的東西了!

+0

它呢,謝謝! – SeptimaEspada