2011-07-31 92 views
2

我在編程一個小計時器。代碼如下:JavaScript:對象問題

var counter = { 
    seconds: 100, 
    clock: function() { 
     $('input').val(this.seconds); 
     this.seconds -= 1; 
     setTimeout(this.clock(), 1000); 
    } 
}; 

counter.clock(); 

http://jsfiddle.net/4ktEG/

不知怎的,我每次運行的代碼,我得到了不同的答案工作的例子。問題是什麼?

+2

這可能會給你更多你在找什麼:HTTP: //jsfiddle.net/4ktEG/13/ –

回答

7

這是你正在尋找的倒計時。

var counter = { 
    seconds: 100, 
    clock: function() { 
     $('input').val(this.seconds); 
     this.seconds -= 1; 
     setTimeout(function(){counter.clock()}, 1000); 
    } 
}; 

counter.clock(); 

http://jsfiddle.net/4ktEG/13/

+0

沒問題。我最初想的是其他事情正在發生,這是我發佈的評論,而不是一個答案。 –

0

用途:

var counter = { 
    seconds: 100, 
    clock: function() { 
     $('input').val(counter.seconds); 
     counter.seconds -= 1; 
     setTimeout(counter.clock, 1000); 
    } 
}; 

counter.clock(); 

你用「本」的功能裏面,你想要的是指「反」的對象。

+0

我仍然沒有做我想做的事。它顯示100,然後什麼也沒有。 – Randomblue

+0

和它有什麼不同?請解釋! – markus

+0

@markus,我爲你添加了一條評論。 – Darm

0

如果你想輸入的顯示「100」,然後消失時的setTimeout被調用時,那麼你必須拿出的「this.clock()」

括號爲此

var counter = { 
seconds: 100, 
clock: function() { 
    $('input').val(this.seconds); 
    this.seconds -= 1; 
    setTimeout(this.clock, 1000); 
} 
}; 

counter.clock(); 
+0

這不是我想要的。我想要一個**計數器**,去100,99,98等。 – Randomblue

+0

好的,我明白你的意思了。 – Jacob

0

當你說

setTimeout(this.clock(), 1000); //the clock method will be called right away. 

使用這個代替

setTimeout(this.clock, 1000); 
0

超時將在全球範圍內執行。因此,處理程序中的「this」將引用全局上下文。您必須將函數綁定到想要的上下文才能達到期望的結果。查看帶有上下文參數的function.callfunction.apply

var counter = { 
    seconds: 100, 
    clock: function() { 
     $('input').val(this.seconds); 
     this.seconds -= 1; 
     var closure = function() { 
      counter.clock.call(counter); 
     }; 

     setTimeout(closure, 1000); 
    } 
}; 

counter.clock(); 
1

jQuery有用於結合thisjQuery.proxy()[docs]方法。

setTimeout($.proxy(counter,'clock'), 1000); 

$.proxy將返回調用counter.clockcounter結合作爲this值的函數。


或者你可以使用這樣的永久綁定countercounter.clock

var counter = { 
    seconds: 100 
}; 

counter.clock = $.proxy(function() { 
    $('input').val(this.seconds); 
    this.seconds -= 1; 
    setTimeout(this.clock, 1000); 
}, counter); 

counter.clock(); 

例子:http://jsfiddle.net/bmYAN/