Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

219
Views
Parent class constructor can't access child fields without Timeout

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?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!