请原谅标题,我不太确定问题是什么......在这一点上,我有点猜测。
这是我第一次尝试在Javascript中重用类。这是它的精简版本:
Countdown = function ( elementID ) {
this.timer = null;
this.output = '';
this.element = document.getElementById(elementID) || document.getElementById('countdown');
}
Countdown.prototype.start = function () {
this.timer = setInterval(this.run, 1000);
}
Countdown.prototype.run = function () {
this.output = 'test';
this.element.innerHTML = this.output; /* THE PROBLEM IS HERE */
}
Countdown.prototype.toCalculatedTime = function () {
this.start();
}
var c = new Countdown();
c.toCalculatedTime();
console.log(c);
我收到错误:
未捕获的类型错误:无法设置未定义的属性"innerHTML"
在指定的行。
首先,是的,有一个 ID 为"倒计时"的元素。我尝试在标记和类中更改元素的名称。我尝试在实例化此类时传递元素名称,但似乎没有区别。
我真的不知道该怎么做。在控制台中,看起来我的类构造得很好。
错误是说this.element
未定义。它未定义的原因是setTimeout
会导致run
在窗口范围内执行。您需要通过使用绑定或闭包来保持范围与此绑定。
this.timer = setInterval(this.run.bind(this), 1000);
或
var that = this;
this.timer = setInterval(function(){ that.run(); }, 1000);