计时器类-Can'找不到变量

Timer Class - Can't find variable

本文关键字:找不到 变量 -Can 计时器      更新时间:2023-09-26

我是JavaScript和面向对象编程的新手。我正在尝试创建一个Timer对象(我认为这是一个对象?)。

我的对象不工作,我得到以下错误:"ReferenceError:找不到变量:countdownTime"(一次又一次)。

我的对象应该创建一个倒计时计时器。用户可以设置计时器倒计时的倒计时时间(以秒为单位)(我的对象的属性)。用户还可以启动和停止我的计时器(方法)。计时器自动停止在0,但用户可以提前停止(例如:用户失去所有生命,还有剩余时间-计时器应该结束)。

为什么这没有按预期工作?

Fiddle:http://jsfiddle.net/bkWTS/

代码:

<div id="output"></div>
<script>
// Timer object
var Timer = function() {
    // PROPERTIES
    this.countdownTime = 120; // amount of time the timer counts down from in seconds
    // METHODS
    // Start timer - starts the countdown timer
    this.Start = function() {
        var timer = setInterval(timerCall, 1000);
    };
    // End timer
    // timer automatically ends when countdown time reaches 0 BUT can be ended early 
    // Example: User looses all lives and there is still time remaining - timer should end
    this.End = function() {
        // Stop timer
        clearInterval(timer);
    };
    function timerCall() {          
        if (countdownTime > 0) {
            // Display time in output div
            document.getElementById("output").innerHTML = countdownTime;
            countdownTime--;    
        } else {
            // Stop timer
            clearInterval(timer);
        }
    }
};
// Create new timer object
var myTimer = new Timer();
// Countdown from 30
myTimer.countdownTime = 30;
// Start the countdown
myTimer.Start();
</script>

您不能看到您的变量,因为您应该像一样引用它

this.countdownTime = ...

在课堂上做以下事情:

var self = this;

然后在timerCall功能中执行

self.countdownTime = ...

这应该可以解决倒计时问题:)