Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

222
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda