0

我有两个不同的对象来创建一个时钟。一个模拟和数字的。除了细微的变化外,它们实际上是相同的。

但是,两者都使用了对象中的许多方法;我希望它们被实例化。所以我需要它们在对象中。例如,如何使用 JavascriptClock的基本方法扩展一个对象?analogueClockdigitalClock

这就是我所拥有的和不起作用的:

通话

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;
    }   
}
4

1 回答 1

3

您可以使用您的基类扩展您的DigitalClockand 。AnalogueClock像下面这样的事情会做。

DigitalClock.prototype = new baseClock();
AnalogueClock.prototype = new baseClock();

所以 DigitalClock 和 AnalogueClock 会继承 baseClock 的方法。另一种选择是使用 mixin 并用它扩展两个类。

于 2013-09-25T14:35:37.437 回答