我有這個JavaScript函數:爲什麼我必須在匿名函數中附加一個Javascript函數調用,以免它立即被調用?
function Card(term, def, terms, curTerm) {
this.term = term;
this.def = def;
this.terms = terms;
this.curTerm = curTerm;
this.show = function() {
that = this;
var html = createCard(that.term, that.def);
$('body').append(html);
$('input[type=text]').focus();
$('.answer').on('click', function(event) {
event.preventDefault();
answer = $(this).parent().serializeArray()[0].value;
// answer correct
if (that.term === answer) {
$('.card').addClass('correct');
$('form').replaceWith('<h2>Correct! ' + that.term + '</h2>');
setTimeout(function() {that.destroy(terms, curTerm + 1);}, 1500);
// answer incorrect
} else {
$('.card').addClass('incorrect');
$('form').replaceWith('<h2>Incorrect! ' + that.term + '</h2>');
setTimeout(function() {that.destroy(terms, curTerm);}, 1500);
}
});
};
我有問題,該生產線是setTimeout(function() {that.destroy(terms, curTerm + 1);}, 1500);
。本來我有setTimeout(that.destroy(terms, curTerm + 1), 1500);
,但它沒有設置超時,它只叫that.destroy
。爲什麼在匿名函數中不會立即調用它?這與封閉有什麼關係?因爲看起來我不得不創建一個閉包,但我還沒有弄清楚他們知道的確實如此。
任何想法將不勝感激。
因爲你正在傳遞一個函數,這是setTimeout期望的。 'setTimeout(that.destroy(terms,curTerm + 1),1500);'立即執行'destroy',並將'destroy'的返回值傳遞給'setTimeout' – Shmiddty