Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't get superclass's property by getter [typescript]

Tags:

typescript

class A
{
    protected _value:number;
    get value()
    {
        return this._value;
    }
}

class B extends A
{
    set value(v:number)
    {
        this._value = v;
    }
}

var b = new B();
b.value = 2;
console.log(b.value);//undefined

Playground

can't get value if subclass just define setter only.

I guess when Object.defineProperty "value" to B.prototype, override the "value" getter setter on A.prototype.

like image 755
Sxd Avatar asked Aug 02 '16 10:08

Sxd


1 Answers

There is a long discussion about this accessors' restriction in this thread.

For the expected behavior either leave both getter and setter in the super class:

class A
{
    protected _value:number;

    get value():number
    {
        return this._value;
    }

    set value(v:number)
    {
        this._value = v;
    }
}

class B extends A
{

}

or alternatively override both on the subclass:

class A
{
    protected _value:number;
    get value():number
    {
        return this._value;
    }

    set value(v:number)
    {
        this._value = v;
    }
}

class B extends A
{

    get value():number
    {
        return this._value;
    }

    set value(v:number)
    {
        this._value = v;
    }

}

If you don't use accessors but use normal methods instead the bahaviour is as expected:

class A
{
    protected _value:number;
    getvalue():number
    {
        return this._value;
    }

}

class B extends A
{

    setvalue(v:number)
    {
        this._value = v;
    }

}

const b:B = new B();
b.setvalue(2);
console.log(b.getvalue());
like image 72
dimitrisli Avatar answered Dec 04 '22 18:12

dimitrisli