たまには、他人が書いたコードをながめてみる?!
カウントダウンのオブジェクト指向版です。製作者はthink49さんです。
勝手にインデントしました。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <title>DownCounter</title> <body> <form action="#"> <p> <input type="text" value="" id="Countdown1" style="width: 10em;"> <input type="button" value="+10d" id="Extend1"> </p> <p> <input type="text" value="" id="Countdown2" style="width: 10em;"> <input type="button" value="+10d" id="Extend2"> </p> </form> <script type="text/javascript"> (function ( ) { // ------- prototype定義 function countDown ( ) { // カウントダウン 初期パラメータ this.currentDay = null; this.countdownId = null; this.extendId = null; this.timeId = null; this.extendTime = 0; // カウントダウン延長時間 (秒) } countDown.prototype.init = function ( parameter ) { this.currentDay = parameter.currentDay ? parameter.currentDay : this.currentDay; // カウントダウン当日の日付オブジェクト this.countdownId = parameter.countdownId ? parameter.countdownId : this.countdownId; // Countdonw要素のIDをセット this.extendId = parameter.extendId ? parameter.extendId : this.extendId; // Extend要素のIDをセット this.timeId = parameter.timeId ? parameter.timeId : this.timeId; }; countDown.prototype.extendCurrentDay = function ( ) { // 入力 (必要であれば、DOMノードはここに書く) this.extendTime += 864000; // カウントダウンを10日延長する }; countDown.prototype.setDate = function ( ) { var now = new Date; // 現在の日付オブジェクトを初期化 this.diff = (this.currentDay.getTime( ) / 1000) - (now.getTime() / 1000) + this.extendTime; // 差分(秒) this.day = Math.floor( this.diff / 86400 ); // カウントダウン パラメータ初期化(日) this.hour = Math.floor( (this.diff % 86400 ) / 3600 ); // カウントダウン パラメータ初期化(時間) this.minuts = Math.floor( (this.diff % 86400 ) / 60) % 60; // カウントダウン パラメータ初期化(分) this.seconds = Math.floor( this.diff % 86400 ) % 60 % 60; // カウントダウン パラメータ初期化(秒) }; function output( id, value ) { // 出力 (必要であれば、DOMノードはここに書く) document.getElementById( id ).value = value; // カウントダウン文字列をセット } function setIntervalCount ( count ) { count.timeId = window.setInterval( function ( ) { count.setDate( ); if( count.diff > 0 ) { output( count.countdownId, count.day + '日' + count.hour + '時間' + count.minuts + '分' + count.seconds + '秒' ); } else { window.clearInterval( count.timeId ); output( count.countdownId, 'ご好評につき、カウントダウンは終了いたしました。' ); // 出力用関数は別途用意し、クロージャにそのまま代入しない (ここがポイント!) } }, 1000 ); // 1秒毎に実行 } function setEvent ( count ) { document.getElementById( count.extendId ).onclick = function ( ) { count.extendCurrentDay( ); // 入力用関数は別途用意し、クロージャにそのまま代入しない (ここがポイント!) }; } function createCountDown( parameter ) { var count = [ ]; for(var i = 0, l = parameter.length; i < l; i++ ) { count[i] = new countDown( ); // コンストラクタ count[i].init( parameter[i] ); setIntervalCount( count[i] ); setEvent( count[i] ); } return count; } var count = createCountDown( [ { currentDay:new Date( 2011, 1, 1 ), countdownId: 'Countdown1', extendId: 'Extend1' }, { currentDay:new Date( 2012, 1, 1 ), countdownId: 'Countdown2', extendId: 'Extend2' } ]); })(); </script>