javascript setTimeout() 第一个参数:表达式错误 [英] javascript setTimeout() first argument: expression error

查看:47
本文介绍了javascript setTimeout() 第一个参数:表达式错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

function Timer() {
 this.initialTime = 0;
 this.timeStart = null;

 this.getTotalTime = function() {
  timeEnd = new Date();
  diff = timeEnd.getTime() - this.timeStart.getTime();

  return diff+this.initialTime;
 };

 this.formatTime = function() {
  interval = new Date(this.getTotalTime());

  return  interval.getHours() + ":" +  interval.getMinutes() + ":" + interval.getSeconds();
 };

 this.start = function() {
  this.timeStart = new Date();

  setTimeout("this.updateTime()", 1000);
 };

 this.updateTime = function() {
  alert(this.formatTime());
  setTimeout("this.updateTime()", 1000);
 };
}


timer = new Timer();
timer.start();

我收到一个错误:

this.updateTime 不是函数

this.updateTime is not a function

有什么想法吗?

谢谢

推荐答案

您的字符串不会在您的对象的上下文中进行计算,因此 this 并不指您认为它会做什么.

Your string is not evaluated in the context of your object, so this doesn't refer to what you think it does.

您不应将字符串参数传递给 setTimeout.相反,您应该传递一个匿名函数,该函数使用保存的 this 副本调用您的方法.

You should not be passing a string argument to setTimeout. Instead, you should pass an anonymous function that calls your method with a saved copy of this.

例如:

var self = this;
setTimeout(function() { self.updateTime(); }, 1000);

self 变量是必需的,因为 setTimeout 的回调也不会在您的对象的上下文中计算.

The self variable is necessary because setTimeout's callback is also not evaluated in the context of your object.

这篇关于javascript setTimeout() 第一个参数:表达式错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆