JavaScript とオブジェクト指向プログラミングは初めてです。Timer オブジェクトを作成しようとしています (これはオブジェクトだと思いますか?)。
オブジェクトが機能していません。次のエラーが表示されます: "ReferenceError: 変数が見つかりません: countdownTime" (何度も何度も)。
私のオブジェクトは、カウントダウン タイマーを作成することになっています。ユーザーは、タイマーがカウントダウンするカウントダウン時間 (秒単位) を設定することができます (私のオブジェクトのプロパティ)。ユーザーは、タイマー (メソッド) を開始および停止することもできます。タイマーは 0 で自動的に停止しますが、ユーザーは早期に停止することができます (例: ユーザーがすべての命を失い、まだ時間が残っている - タイマーは終了する必要があります)。
これが期待どおりに機能しないのはなぜですか?
フィドル: 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>