2012-12-03 98 views
0

我試圖在Javascript中創建一個計時器,我對如何實現它有特定的問題。Javascript中的命名空間類

現在是這樣的

function CountUpTimer(seconds,name,targetId,submitButtonId){ 
this.time = seconds; 
this.currentTime = 0; 
this.minutes = Math.floor(seconds/60); 
this.submitButtonId = submitButtonId; 

this.seconds = seconds - this.minutes*60; 
this.currentSeconds = 0; 
this.currentMinutes = 0; 
this.targetId = targetId; 
this.name = name; 
this.isPaused = false; 
this.init = function(){ 
    setInterval(this.name + ".tick()",1000); 
} 

this.pause = function(){ 
    this.isPaused = true; 
} 
this.unpause = function(){ 
    this.isPaused = false; 
} 
this.tick = function(){ 
    if(this.isPaused == false){ 
    if(this.currentTime <= this.time){ 
     if(this.currentSeconds == 59){ 
      this.currentSeconds = 0; 
      this.currentMinutes++; 
     } 
     this.updateTimer(); 
     this.currentTime++; 
     this.currentSeconds++; 
    } else{ 
     this.endTiming(); 
    } 
} 
} 

現在,這個問題是我不能動態地創建CountUpTimer對象,因爲我需要知道的變量,我分配給該對象的名稱。有什麼辦法可以解決這個問題 - 所以我們來說說一下吧 -

setInterval(this.tick(),1000); 

回答

2

使用回調時,會丟失執行時的上下文。 您應該使用bind來保持上下文。

setInterval(this.tick.bind(this),1000); 

更多細節here

+0

工作 - 謝謝 – praks5432

+0

請注意,'Function.bind'是一個相對較新的功能,並不支持在許多瀏覽器。 – David

+0

我爲自己創建的[Live test case](http://jsfiddle.net/weWqe/)然後意識到你是正確的。 :) –

1
this.init = function(){ 
    var self = this; 
    setInterval(self.tick(),1000); 
} 

保持引用原始對象,因爲使用這setInterval的將是在錯誤的對象上下文(文件)。

0

你可以這樣做:

var self = this; 
setInterval(function() { 
    self.tick() 
}, 1000); 

或者使用Function.bind,如果你是罰款與非傳統支持。