0

我正在尝试在 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);

?

4

3 回答 3

2

使用回调时,您会在执行时丢失上下文。您应该使用bind来保持上下文。

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

更多细节在这里

于 2012-12-03T09:06:39.053 回答
1
this.init = function(){
   var self = this;
   setInterval(self.tick(),1000);
}

Keep the reference to original object, because using this in setInterval will be in the wrong object context (document).

于 2012-12-03T09:08:47.350 回答
0

你可以做:

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

或者Function.bind,如果您对非传统支持没问题,请使用。

于 2012-12-03T09:12:04.563 回答