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.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With