Full disclosure: I have posted this in an issue here.
I am working on a bit of code that I want to use the inheritance of ECMAScript 2015, but I am struggling with some inheritance issues.
Say I have the following classes defined:
A = class A {
constructor(value, options) {
this.value = value;
this.options = options;
console.log('constructor this: ', this);
}
get value() {
return this._value;
}
set value(value) {
this._value = value;
}
get options() {
return this._options;
}
set options(options) {
this._options = options;
}
get validationErrors() {
// Do standard validations for all classes of type A here
console.log('A.validationErrors this: ', this);
var validationErrs = [];
if (options && options.required && !value) {
validationErrs.push('Value is required');
}
return validationErrs;
}
}
B = class B extends A {
get validationErrors() {
console.log('B.validationErrors this: ', this);
var valErrs = super.validationErrors;
// Do custom validations for class B here
return valErrs;
}
}
var b = new B('val', {required: true});
var valErrs = b.validationErrors;
Strangely, what I see in the logs is:
constructor this: B{_value: "val", _options: {required: true}}
B.validationErrors this: B{_value: "val", _options: {required: true}}
A.validationErrors this: A{}
Where this confuses me is that I would think the value and options would be stored in the parent, since the call is in the parent class A
, but when the code runs it looks like the setters are run in the context of B
instead. I have tried writing an overriding constructor in B
that calls the constructor for A
, but that didn’t work either. I simply can’t get my head wrapped around why this doesn’t work.