I encountered a puzzling scenario while coding that has left me perplexed.
Here's the situation: I am extending a class from a library, which serves as the "Parent"-class. It allows its subclasses to override the init-method for custom initialization.
However, the behavior of the second child class is not what I expected. The only distinction between the two classes is the declaration of a member variable. In typical JavaScript, I would not approach it this way, but since I'm using Typescript, the compiled result includes a "member;" (in my case, even without assigning a value). Consequently, the output shows "undefined".
I suspect this issue arises when the variable is set within an overridden function called by the parent constructor.
Could someone shed some light on why this anomaly occurs?
class Parent {
constructor(initArgs) {
this.init(initArgs);
}
init() {}
}
class ChildTest1 extends Parent {
init(args) {
this.member = args;
}
test() {
console.log(`Member of ChildTest1 has value of "${this.member}"`);
}
}
class ChildTest2 extends Parent {
member = "default";;
init(args) {
this.member = args;
}
test() {
console.log(`Member of ChildTest2 has value of "${this.member}"`);
}
}
new ChildTest1("Hello World").test();
new ChildTest2("Hello World").test();
The code produces the following output:
Member of ChildTest1 has a value of "Hello World"
Member of ChildTest2 has a value of "default"