Question

I have two different objects to create a clock. A analogue and digital one. THey're practically the same except for minor changes.

Alot of methods in the object are used by both however; I want them to be instanced though. So i need them in the object. How can I extend for example a Clock object with the basic methods to analogueClock and digitalClock with Javascript?

This is what I have and doesn't work:

the call

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

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

And the functions

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;
    }   
}
Was it helpful?

Solution

You can extend your DigitalClock and AnalogueClock with your base class. Something like following would do.

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

So DigitalClock and AnalogueClock will inherit the methods of baseClock. Another option could be to use mixin and extend both classes with it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top