获取/设置面向对象的JavaScript

时间:2016-10-14 10:36:25

标签: javascript object get set

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;

我得到的结果是:

0undefined:0undefined:0undefined

我认为这个问题与我的获取/设置属性有关。

还努力让时钟刻录,但是一旦我将Tick()函数放入for循环中,这可能是可以解决的。

1 个答案:

答案 0 :(得分:0)

您正在Counter构造函数(即Counter.Value)上创建访问者属性,而不是在当前创建的实例上:

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