我正在使用JavaScript编写倒数计时器。相当基本。在时间方面只使用setInterval
。我使用存储函数和变量的原型方法编写它,所以我可以创建一个“类”。Javascript“Class”via Prototypes - 变量未定义
我以这种方式调用代码。
function testTimer() {
var newTimer = new CDTimer($("#voteTimer"),30,"");
newTimer.start();
}
当下面代码运行,console.log
正在打印undefined
或NaN
。
function CDTimer (target, duration, callback) {
this.target = target;
this.duration = duration;
this.callback = callback;
}
CDTimer.prototype.start = function() {
this.start = new Date().getTime();
this.interval = setInterval(this.update, 1000);
}
CDTimer.prototype.update = function() {
console.log(this.duration, this.start);
this.elapsed = this.duration - (new Date().getTime() - this.start)/1000
if (this.elapsed < 0) {
clearInterval(this.interval);
this.callback();
}
else {
console.log(this.elapsed);
$(this.target).text(this.elapsed);
}
}
CDTimer.prototype.stop = function() {
clearInterval(this.interval);
}
我一定错过了一些愚蠢的东西。我的变量及其价值发生了什么?
感谢您的洞察力。
你期望'this'指什么?你还没有用你的构造函数创建任何对象。 –