I want to create a class hierarchy in vanilla JavaScript where a base class defines a common architecture and several inheriting classes add fields and functionality to it.
I don't understand why a subclass field not present in the base class remains undefined when it is set in an overridden function in the subclass via the base class constructor.
Is this to do with the scope of this
in the baseclass constructor?
What would be the correct way of doing something like this?
//A base class with just one field
class Base{
field1;
constructor(){
//Call an overridden function of a subclass if it has been defined
this.setParameters();
}
setParameters(){
this.field1 = "BASE_VALUE"
}
}
//A subclass with the field of the base one and an additional unique field
class Sub extends Base{
field2;
//Override the base class function
setParameters(){
this.field1 = "SUB_VALUE_1";
this.field2 = "SUB_VALUE_2";
}
}
var base = new Base();
console.log(base); // field1 is "BASE_VALUE" as expected
var sub = new Sub();
console.log(sub); // field2 is undefined but I would expect it to be "SUB_VALUE_2"