【问题标题】:Call Javascript Object Method with SetInterval()使用 SetInterval() 调用 Javascript 对象方法
【发布时间】:2013-08-18 06:51:31
【问题描述】:

这是一个fiddle

我正在尝试创建一个使用 moment.js 的倒计时对象(我更喜欢使用 Date() 的插件)

var Countdown = function(endDate) {
    this.endMoment = moment(endDate);

    this.updateCountdown = function() {
        var currentMoment, thisDiff;

        currentMoment = moment();
        thisDiff = (this.endMoment).diff(currentMoment, "seconds");

        if (thisDiff > 0)
            console.log(thisDiff);
        else {
            clearInterval(this.interval);
            console.log("over");
        }
    }

    this.interval = setInterval(this.updateCountdown(), 1000);
}

然后我创建一个倒计时实例,如下所示:

var countdown = new Countdown("January 1, 2014 00:00:00");

但是,该功能似乎只运行一次。有任何想法吗?我应该改用 setTimeout() 吗?

【问题讨论】:

  • 在您致电setInterval 时尝试this.updateCountdown
  • 似乎没有引用该对象(抛出错误'无法调用未定义的方法'diff'):jsfiddle.net/zCFr5/2
  • 你需要这样做jsfiddle.net/zCFr5/3
  • 啊,好吧,我明白了,创建一个本地变量来存储它。你想把它写成答案,这样我就可以选择你的答案了吗?

标签: javascript object methods setinterval momentjs


【解决方案1】:

您应该将 reference 传递给函数,而不是其执行的结果。 此外,您需要一些额外的“魔法”才能以这种方式调用方法。

var me = this;
this.interval = setInterval(function () {
    me.updateCountdown();
}, 1000);

【讨论】:

  • 您可以使用Function.bind,而不是保存对this 的引用。 stackoverflow.com/a/6065221/139010
  • 是的,但它不适用于旧版浏览器。并且没有相关的框架。
  • 似乎仍然无法正常工作,这是更新后的小提琴:jsfiddle.net/zCFr5/1
  • 我链接的答案是:Function.bind 很容易填充。
【解决方案2】:

您可以将 this 上下文存储为局部变量,如下所示:

var Countdown = function(endDate) {
  var self = this;
  this.endMoment = moment(endDate);

  this.updateCountdown = function() {
      var currentMoment, thisDiff;

      currentMoment = moment();
      thisDiff = (self.endMoment).diff(currentMoment, "seconds");

      if (thisDiff > 0)
          console.log(thisDiff);
      else {
          clearInterval(self.interval);
          console.log("over");
      }
  }

  this.interval = setInterval(this.updateCountdown, 1000);
}

或者你可以直接使用你的变量,例如:

var Countdown = function(endDate) {
  var endMoment = moment(endDate);

  this.updateCountdown = function() {
      var currentMoment, thisDiff;

      currentMoment = moment();
      thisDiff = (endMoment).diff(currentMoment, "seconds");

      if (thisDiff > 0)
          console.log(thisDiff);
      else {
          clearInterval(interval);
          console.log("over");
      }
  }

  var interval = setInterval(this.updateCountdown, 1000);
}

我更喜欢第二种方法 - fiddle

【讨论】:

    猜你喜欢
    • 2011-11-11
    • 2019-10-02
    • 2020-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多