在阅读了 Douglas Crockford 的“JavaScript: The Good Parts”之后,我尝试实现这样的计时器。它有私有变量(秒、小时、分钟)和三个公共方法:开始、停止和继续:
var timer = function() {
var that = {};
var seconds = 0;
var hours = 0;
var minutes = 0;
var myTimer;
that.getTime = function() {
var time = hours + " : " + minutes + " : " + seconds;
return time;
}
that.start = function() {
seconds += 1;
if(seconds >= 60) {
seconds -= 60;
minutes += 1;
}
if(minutes == 60)
hours += 1;
document.getElementById('hours').innerHTML = hours;
document.getElementById('minutes').innerHTML = minutes;
document.getElementById('seconds').innerHTML = seconds;
myTimer = setTimeout(function() {
start();
}, 1000);
};
that.stop = function() {
clearTimeout(myTimer);
}
that.reset = function() {
seconds = 0;
hours = 0;
minutes = 0;
clearTimeout(myTimer);
document.getElementById('hours').innerHTML = hours;
document.getElementById('minutes').innerHTML = minutes;
document.getElementById('seconds').innerHTML = seconds;
}
return that;
};
然后,我开始了它:
<body onload="var t = timer();t.start();">
<h1>Digital Clock</h1>
<div id="wrap">
<div>
<ul>
<li id="hours"></li>
<li> : </li>
<li id="minutes"></li>
<li> : </li>
<li id="seconds"></li>
</ul>
</div>
</div>
<br/>
</body>
谁能告诉我我犯了什么错误?
更新:最后,我发现了问题。当您在另一个函数(例如内部函数)中使用一个函数时,“this”绑定到global,而不是外部函数。因此,在语句 start() 中,js 将尝试在全局对象中查找函数。当然,没有这样的功能。在这里,我找到了两个解决方案:
用“那个”
myTimer = setTimeout(function() { that.start(); }, 1000);
保存上下文:
var timerInstance = 这个;
myTimer = setTimeout(function() { timerInstance.start(); }, 1000);
希望这会帮助你。