0
我有兩個不同的對象來創建一個時鐘。一個模擬和數字的。除了微小的變化之外,這幾乎是一樣的。使用Javascript擴展方法
然而,對象中的許多方法都被使用;我希望他們被實例化。所以我需要他們在對象中。我怎麼能擴展例如一個Clock
對象與基本的方法analogueClock
和digitalClock
與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;
}
}
我在哪裏可以使用.prototype?在創建一個新的對象時,在函數上面還是在函數中? – CaptainCarl
首先定義baseClass和任何派生類。在定義派生類之後,從baseClass擴展它。所以例如定義'DigitalClock'後,擴展它'DigitalClock.prototype = new baseClock();'。 – Ehtesham
當我回家時,我會給它一個鏡頭。我會批准!謝謝! – CaptainCarl