2013-09-25 100 views
0

我有兩個不同的對象來創建一個時鐘。一個模擬和數字的。除了微小的變化之外,這幾乎是一樣的。使用Javascript擴展方法

然而,對象中的許多方法都被使用;我希望他們被實例化。所以我需要他們在對象中。我怎麼能擴展例如一個Clock對象與基本的方法analogueClockdigitalClock與Javascript?

這是我並不起作用:

通話

if (clockType == 'digital') { 
    clk = new DigitalClock(theClockDiv); 
} else if (clockType == 'analogue') { 
    clk = new AnalogueClock(theClockDiv); 
} 

baseClock = new baseClock();  
$.extend({}, clk, baseClock); 

而且功能

function DigitalClock(theDigitalClockParent, indicatedTime) { 
    this.indicatedTime = indicatedTime; 
    this.interval = null; 
    this.buildClock = function() { 
     //CUSTOM THINGS HERE 
    } 

    this.setCurrentTime(); 
    this.buildClock(); 
    this.startRechecker(); 
} 


function AnalogueClock(theAnalogueClockParent, indicatedTime) { 
    this.indicatedTime = indicatedTime; 
    this.interval = null; 
    this.buildClock = function() { 
     //CUSTOM THINGS HERE 
    } 

    this.setCurrentTime(); 
    this.buildClock(); 
    this.startRechecker(); 
} 

function baseClock() { 
    this.setCurrentTime = function() { 
     if (this.indicatedTime != undefined) { 
      this.date = new Date(railsDateToTimestamp(this.indicatedTime)); 
     } else { 
      this.date = new Date(); 
     } 

     this.seconds = this.date.getSeconds(); 
     this.minutes = this.date.getMinutes(); 
     this.hours = this.date.getHours(); 
    } 

    this.startInterval = function() { 

     //Use a proxy in the setInterval to keep the scope of the object. 
     this.interval = setInterval($.proxy(function() { 
      //console.log(this); 
      var newTime = updateClockTime(this.hours, this.minutes, this.seconds); 
      this.hours = newTime[0]; 
      this.minutes = newTime[1]; 
      this.seconds = newTime[2]; 
      this.buildClock(); 
     }, this), 1000); 
    } 

    this.stopInterval = function() { 

     window.clearInterval(this.interval); 
     this.interval = null; 
    } 
} 

回答

3

您可以擴展您的DigitalClockAnalogueClock你的基類。像下面的東西會做。

因此,DigitalClock和AnalogueClock將繼承baseClock的方法。另一種選擇可以是使用mixin並使用它擴展兩個類。

+0

我在哪裏可以使用.prototype?在創建一個新的對象時,在函數上面還是在函數中? – CaptainCarl

+0

首先定義baseClass和任何派生類。在定義派生類之後,從baseClass擴展它。所以例如定義'DigitalClock'後,擴展它'DigitalClock.prototype = new baseClock();'。 – Ehtesham

+0

當我回家時,我會給它一個鏡頭。我會批准!謝謝! – CaptainCarl