自定义类中的本机 JS:"Uncaught TypeError: Cannot set property 'innerHTML' of undefined"



请原谅标题,我不太确定问题是什么......在这一点上,我有点猜测。

这是我第一次尝试在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);

相关内容

最新更新