Tauntaunwampa Tauntaunwampa - 1 month ago 22
Javascript Question

Get/Set in Object-Oriented JavaScript

Counter = function ()
{
var _count;

_count = 0;

this.AddCounter = function()
{
_count++;
};

this.Reset = function ()
{
_count = 10;
};

Object.defineProperty( Counter, 'Value', {
get : function(){ return _count; },
set : function(){ _count = Value; },
configurable: true } );

}

Clock = function ()
{
var second = new Counter();
var minute = new Counter ();
var hour = new Counter();

this.Reset = function()
{
second.Reset();
minute.Reset();
hour.Reset();
};

this.Tick = function()
{
second.AddCounter();
if (second.Value == 60)
{
second.Reset();
minute.AddCounter();
if (minute.Value == 60)
{
minute.Reset();
hour.AddCounter();
}
}
};

this.ReadClock = function()
{
var sz = 0;
var mz = 0;
var hz = 0;

if (second.Value == 9)
{sz = null;}
if (minute.Value == 9)
{mz = null;}
if (hour.Value == 9)
{hz = null;}

document.getElementById("clock").innerHTML = ("" + hz + hour.Value + ":" + mz + minute.Value + ":" + sz +second.Value);
};
}

function Init()
{
var myClock = new Clock();
myClock.Tick();
myClock.ReadClock();
}

window.onload = Init;


The result I'm getting is:

0undefined:0undefined:0undefined


I think the issue is something to do with my Get/Set Property.

Also struggling to get the clock to tick, but that might be solvable once I put the
Tick()
function in a for loop.

Answer

You're creating the accessor property on the Counter constructor function (i.e. Counter.Value), not on the currently created instance:

function Counter() {
    var _count = 0;

    this.AddCounter = function() {
        _count++;
    };

    this.Reset = function() {
        _count = 10;
    };

    Object.defineProperty(this, 'Value', {
//                        ^^^^
        get: function(){ return _count; },
        set: function(val){ _count = val; },
        configurable: true
    });
}