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 is not a function
有什么想法吗?
谢谢
最佳答案
您的字符串未在您的对象的上下文中求值,因此 this
并未引用您认为的内容。
您不应将字符串参数传递给 setTimeout
。相反,您应该传递一个匿名函数,该函数使用 this
的已保存副本调用您的方法。
例如:
var self = this;
setTimeout(function() { self.updateTime(); }, 1000);
self
变量是必需的,因为 setTimeout
的回调也不会在您的对象的上下文中进行评估。
关于javascript setTimeout() 第一个参数 : expression error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2604597/