I was trying to override a Parent Class's set method for a variable (both set and get method implemented) in order to extend certain functionalities in the Child Class. However in doing so, whenever I tried to get the value of variable using get method I got undefined as a returned value.
Parent Class
//Parent Class
class Parent {
constructor() {
this._hidden = 10;
}
get hidden() {
return this._hidden;
}
set hidden(val) {
this._hidden = val *10;
}
}
Child Class
//Child class overriding Parent's set hidden() method
class Child extends Parent {
constructor() {
super();
}
set hidden(val) {
this._hidden = val *20;
}
}
Implementation
let parent = new Parent();
parent.hidden = 10;
console.log("Parent",parent.hidden);
let child = new Child();
child.hidden = 10;
console.log("Child",child.hidden);
OutPut
I did get a way around it by making a get method in the child class and having it call the super.hidden
to get the variable. I want to know why overriding of get and set is not possible in my case or any case? I did a few turn around and tried several cases with the following snippet.
Example
//Parent Class
class Parent {
constructor() {
this._hidden = 10;
}
get hidden() {
return this._hidden;
}
set hidden(val) {
this._hidden = val *10;
}
}
//Child without any overriding
class Child1 extends Parent {
constructor() {
super();
}
}
//Child class overriding Parent's set hidden() method
class Child2 extends Parent {
constructor() {
super();
}
set hidden(val) {
this._hidden = val *20;
}
}
//TO get the job done
class Child3 extends Parent {
constructor() {
super();
}
get hidden() {
return super.hidden;
}
set hidden(val) {
this._hidden = val *20;
}
}
let parent = new Parent();
parent.hidden = 10;
console.log("Parent",parent.hidden);
let child1 = new Child1();
child1.hidden = 10;
console.log("Child1",child1.hidden);
let child2 = new Child2();
child2.hidden = 10;
console.log("Child2",child2.hidden);
let child3 = new Child3();
child3.hidden = 10;
console.log("Child3",child3.hidden);
Why does this happen and what can I do further?