0

I am making an application using JavaScript. One thing that I noticed is that when I call super() from child class constructor, I cannot use child class fields.

For example:

class Parent {
    constructor() {
        console.log(this.x);
    }
}
class Child extends Parent {
    x = 5;
    constructor() {
        super();
    }
}
Output: undefined

As you see, the parent constructor cannot access the x field of the child constructor. There are similar questions on stackoverflow like:

Access JavaScript class property in parent class

The solution they give is to use an init() method on the Parent class. I realized that every method other than the constructor of the Parent class has access to child fields.

class Parent {
    init() {
        console.log(this.x);
    }
}
class Child extends Parent {
    x = 5;
    constructor() {
        super();
        this.init();
    }
}
Output: 5

However, I can also get access to the x field by using Timeout with delay of 0:

class Parent {
    constructor() {
        setTimout(() => console.log(this.x), 0);
    }
}
class Child extends Parent {
    x = 5;
    constructor() {
        super();
    }
}
Output: 5

All the answers on stackoverflow give the solution, but nobody explains how and why this happens. So my question is:

1. Why the constructor doesn't have access to fields of the child class?

2. Why adding a timeout function gives access to the fields of the child class?

DarkBee
  • 16,592
  • 6
  • 46
  • 58
Meet Shah
  • 612
  • 1
  • 6
  • 13
  • 1
    The field `x = 5;` acts as `this.x = 5;` inside the constructor _after_ the `super` call. `this` cannot be used in the constructor of a derived class before `super`. I think something related is mentioned in [How does the "this" keyword work?](/q/3127429/4642212). – Sebastian Simon Nov 10 '21 at 08:42
  • Sorry I forgot to add ```extends Parent```. – Meet Shah Nov 10 '21 at 08:45
  • So you mean that ```x = 5``` is executed as ```this.x = 5``` inside the constructor? And so until we don't call the ```super()``` method, this will not point to anything? – Meet Shah Nov 10 '21 at 08:46
  • See [Why isn't this allowed before super()](/q/43539654/4642212). `this` only exists once execution reaches the base class through a series of `super` calls. Only after those `super` calls, class fields get applied; they can only be added as properties to `this`. A `this` has to exist first. – Sebastian Simon Nov 10 '21 at 08:55

0 Answers0