Encountered a peculiar issue where the values assigned to a field in a class were mysteriously overwritten with 'undefined' after running a constructor.
This problem seemed to be related to this GitHub issue, which is connected to this proposal.
Below is the code snippet that reproduces the issue:
While I can appreciate some of the rationale behind this decision, experts in Javascript and its intricacies have extensively debated it. I assumed their choice was more informed than one I could make myself.
However, the issue remains unsettling as it creates the illusion of functioning code until suddenly everything becomes undefined once the constructor completes its execution. So, my question is: what is the proper way to handle such situations? One workaround involves embedding something like myField: string = this.myField
, but this code can be confusing for those who are not well-versed in the underlying mechanisms, leading most people to dismiss it as pointless.
I am grappling with finding the idiomatic approach for initializing fields within a constructor, and all my attempts thus far seem convoluted and potentially fall under the umbrella of an anti-pattern.
class Base {
constructor(dto?){
if(dto){
this.updateFromDTO(dto);
}
}
updateFromDTO(dto) : this{
return this;
}
}
class Extends extends Base {
myField: string;
updateFromDTO(dto) {
super.updateFromDTO(dto);
console.log('I was called');
this.myField = "weee";
console.log(this.myField);
return this;
}
}
console.log(new Extends("123"));//logs 'I was called', 'weee', then the extends object which has myField as undefined.
Babel configuration required to reproduce this behavior:
const DEVELOPMENT = 'production' !== process.env.NODE_ENV
module.exports = {
presets: [
["@babel/preset-env", {useBuiltIns: "entry"}],
"@babel/preset-react",
"@babel/typescript"
],
plugins: [
"@babel/plugin-proposal-class-properties",
"@babel/plugin-proposal-export-default-from",
"@babel/plugin-syntax-dynamic-import",
["@babel/plugin-transform-runtime", {"regenerator": true}],
"@babel/plugin-transform-classes",
],
}