首页 > 解决方案 > 一页上相同javascript类的两个实例引用相同的实例

问题描述

我正在尝试编写一个倒数计时器脚本,它只适用于页面上的一个实例,但如果我添加第二个实例,则只有第二个开始计数。

我发现如果我同时加载两个,但只为第二个调用 start,第一个会触发。看来它们的范围不正确。

我正在使用新的类语法,所以我认为它应该按原样工作,但我显然遗漏了一些东西。我希望有人可以帮助我理解我做错了什么。我的主要语言是 PHP,但我对 JS 的了解并不如我所愿。

这是我的要点的链接,其中包含代码:https ://gist.github.com/kennyray/b35f4c6640be9539c5d16581de7714e0

class CountdownTimer {

	constructor(minutesLabel = null, secondsLabel = null) {
		self = this;
		this.minutesLabel = minutesLabel;
		this.secondsLabel = secondsLabel;
		this.totalSeconds = (this.minutesLabel.textContent / 60) + this.secondsLabel.textContent;
		this.timer = null;
	}
	
	set minutesLabel(value) {
		self._minutesLabel = value;
	}
	
	set secondsLabel(value) {
		self._secondsLabel = value;
	}
	
	get minutesLabel() {
		return self._minutesLabel;
	}
	
	get secondsLabel() {
		return self._secondsLabel;
	}
	
	
    setTime() { 
      self.totalSeconds--;
	  if (parseInt(self.minutesLabel.innerHTML) == 0 && parseInt(self.secondsLabel.innerHTML) == 0) { self.stopTimer; return;}
	  
	  if (self.secondsLabel.innerHTML.textContent < 0) { self.secondsLabel.innerHTML = 59 }
	  if (self.minutesLabel.innerHTML.textContent < 0) { self.minutesLabel.innerHTML = 59 }
	  self.secondsLabel.innerHTML = self.pad((self.totalSeconds % 60));
      self.minutesLabel.innerHTML = self.pad(Math.floor(self.totalSeconds / 60));
	  
    } 
    
	pad(val) {
    		var valString = val + "";
        if (valString.length < 2) {
            return "0" + valString;
		} else {
            return valString;
        } 
    }
    
    resetTimer() {
        clearInterval(self.timer);
        self.totalSeconds = 0;
        self.secondsLabel.innerHTML = self.pad(self.totalSeconds % 60);
        self.minutesLabel.innerHTML = self.pad(parseInt(self.totalSeconds / 60));   
    }
    
    startTimer() {
    	self.timer = setInterval(self.setTime, 1000);
    }
	
	stopTimer() {
    	clearInterval(self.timer);
    }

}

const t1 = new CountdownTimer(document.getElementById("minutes1"), document.getElementById("seconds1"));
t1.startTimer();


const t2 = new CountdownTimer(document.getElementById("minutes"), document.getElementById("seconds"));
console.log(t1.startTimer() === t2.startTimer());
t2.startTimer();
<label id="minutes1">01</label>:<label id="seconds1">10</label>
<br>
<label id="minutes">00</label>:<label id="seconds">10</label>

标签: javascriptecmascript-6es6-class

解决方案


您正在声明一个全局变量self(为什么要这样做?),它会被覆盖。只this在课堂上使用。

然后你的 startTimer 函数需要

 startTimer() {
    this.timer = setInterval(this.setTime.bind(this), 1000);
  }

也许应该检查是否已经有一个间隔并this.timer完全清除

startTimer() {
    if (this.timer) this.stopTimer();
    this.timer = setInterval(this.setTime.bind(this), 1000);
}

stopTimer() {
    clearInterval(this.timer);
    this.timer = null;
}

推荐阅读