我有两个不同的对象来创建一个时钟。模拟和数字。除了微小的变化之外,它几乎是一样的。
然而,对象中使用了很多方法;我希望它们能够被实例化。所以我需要它们在对象中。如何使用Javascript将基本方法的Clock
对象扩展为analogueClock
和digitalClock
?
这就是我拥有和不起作用的地方:
电话
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;
}
}
答案 0 :(得分:3)
您可以使用基类扩展DigitalClock
和AnalogueClock
。像下面这样的事情就可以了。
DigitalClock.prototype = new baseClock();
AnalogueClock.prototype = new baseClock();
因此DigitalClock和AnalogueClock将继承baseClock的方法。另一个选择可能是使用mixin并用它扩展这两个类。