首页 > 解决方案 > 属性变得未定义

问题描述

我正在制作一个时钟类,它会每秒生成时间。

class Clock {
  constructor(template) {
    this._template = template;
    this._timer = null;
  }

  render() {
    var date = new Date();

    var output = this._template
      .replace("h", date.getHours())
      .replace("m", date.getMinutes())
      .replace("s", date.getSeconds());

    console.log(output);
  }

  start() {
    this.render();
    this._timer = setInterval(this.render, 1000);
  }
}

var clock = new Clock("h:m:s");
clock.start();

起初,这是正常的。输出与我期望的相同。那么,就会出现错误 TypeError: Cannot read property 'replace' of undefined。真奇怪。为什么我的template属性变得未定义?

标签: javascript

解决方案


您正在传递this.render给该setTimeout函数,因此this上下文已更改。你需要.bind(this),一切都会按预期工作。

class Clock {
  constructor(template) {
    this._template = template;
    this._time = null;
  }

  render() {
    var date = new Date();

    var output = this._template
      .replace("h", date.getHours())
      .replace("m", date.getMinutes())
      .replace("s", date.getSeconds());

    console.log(output);
  }

  start() {
    this.render();
    this._timer = setInterval(this.render.bind(this), 1000); // <-- here
  }
}

new Clock('h:m:s').start();


推荐阅读