I have two classes one of them is the parent class and the other one is the child class and what I'm trying to achieve is to access the values of child classe's instance level variables by using this keyword in a field that is declared in the parent class. But when I try to do so it returns undefined. Can anyone please explain what might be going wrong here. Below I've pasted a code snippet for your reference. Thanks!
class Parent {
someField = {
someValue: 'Values are ::: ' this.value1 ' ' this.value2,
childType2: "Some gibberish"
}
initialize(childType1) {
this.someField = this.someField[childType1];
}
}
class Child extends Parent {
value1 = "someValue 1"
value2 = "someValue 2"
}
const child = new Child();
child.initialize("someValue");
console.log(child.someField);
CodePudding user response:
It's not that this is wrong, it's a matter of timing. Your code initializing someField runs as part of the Parent constructor, before your code initializing value1 and value2 runs (as part of the Child constructor). So you get undefined when reading them.
The way public fields work in JavaScript, the definition of the property defined by the field declaration becomes part of the constructor's code, exactly as though you had written it at the beginning of the constructor (just after any call to super) (but [effective] using Object.defineProperty, not just simple assignment; details). That is, your code is the effectively the same as this:
class Parent {
constructor() {
Object.defineProperty(this, "someField", {
value: {
someValue: 'Values are ::: ' this.value1 ' ' this.value2,
childType2: "Some gibberish"
},
writable: true,
enumerable: true,
configurable: true
});
}
initialize(childType1) {
this.someField = this.someField[childType1];
}
}
class Child extends Parent {
constructor() {
super();
Object.defineProperty(this, "value1", {
value: "someValue 1",
writable: true,
enumerable: true,
configurable: true
});
Object.defineProperty(this, "value2", {
value: "someValue 2",
writable: true,
enumerable: true,
configurable: true
});
}
}
const child = new Child();
child.initialize("someValue");
console.log(child.someField);
